0
我有一個片段內的按鈕。 moneyBtn
被發現使用val button:Button? = view?.findViewById(R.id.moneyBtn) as Button?
我使用?
,因爲IDE會拋出語法錯誤。片段按鈕onClickListener不執行
的button
目前正在利用其setOnClickListener:
button?.setOnClickListener {
moneyGetten()
mEditor.putInt("money", money++)
mEditor.commit()
moneyGetten()
Log.d("BUTTON CLICKED", "!")
}
我的理論:該視圖將不會被發現,出於某種原因,所以findView將與null
響應,?
被「保護」的OnClickListener。
這裏是我的XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="de.fosefx.clickergame.Generator">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/plus1label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="135dp"
android:text="+1"
android:textAppearance="@style/TextAppearance.AppCompat.Display1" />
<Button
android:id="@+id/moneyBtn"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="67dp"
android:text="CLICK ME" />
</RelativeLayout>
</FrameLayout>
你應該用調試器測試你的理論。甚至通過記錄這些變量的值。 – zsmb13
嘗試把它作爲var而不是val。 –