1

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>
wenus
  • 1,345
  • 6
  • 24
  • 51

2 Answers2

4

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
}
georkost
  • 588
  • 6
  • 12
  • but I have to do this before returning View right? On onCreateView – wenus Nov 27 '20 at 11:58
  • You would do what @georkost says in `onViewCreated` to be exact, it can also be done in onCreateView. Remove the `onStart` method completely. See here for more https://stackoverflow.com/a/38718205/1133011 – David Kroukamp Nov 27 '20 at 12:06
1

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)
Timoth
  • 11
  • 2