Reputation: 1515
I have a problem, becasu my Fragment class cant'f find Id of my Button in Fragment. I inflate Ciew, but this still not working, and I want to set on Btn ClickListener, but I cant. How can I fix it?
Kotlin code of my Fragment:
class FragmentMain : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_main, container, false)
}
override fun onStart() {
super.onStart()
play.setOnClickListener { <--- here is error, cause kotlin don't know this button??
Toast.makeText(context, "test", Toast.LENGTH_SHORT).show()
}
}
}
And XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
tools:context=".FragmentMain">
<LinearLayout
android:id="@+id/container_frag"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
>
<Button
android:id="@+id/play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Play" />
<Button
android:id="@+id/about"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="About" />
</LinearLayout>
Upvotes: 1
Views: 3318
Reputation: 11
As @georkost said, declare your button reference in onViewCreated but call the findViewById method from your view :
val button = view.findViewById<Button>(R.id.play)
Upvotes: 1
Reputation: 618
You have to get a reference to the button first so you must do something like the following
val button = findViewById<Button>(R.id.play)
button.setOnClickListener { _ ->
//do what you want after click inside here
}
Upvotes: 4