【发布时间】:2020-11-27 11:52:33
【问题描述】:
我有一个问题,因为我的 Fragment 类无法在 Fragment 中找到我的 Button 的 Id。我给 Ciew 充气,但这仍然不起作用,我想在 Btn ClickListener 上进行设置,但我不能。我该如何解决?
我的 Fragment 的 Kotlin 代码:
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()
}
}
}
和 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>
【问题讨论】: