【问题标题】:Kotlin can't find button Id in fragment, why?Kotlin 在片段中找不到按钮 ID,为什么?
【发布时间】: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>

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    您必须首先获得对该按钮的引用,因此您必须执行以下操作

    val button = findViewById<Button>(R.id.play)
    button.setOnClickListener { _ ->
       //do what you want after click inside here
    }
    

    【讨论】:

    • 但是在返回 View 之前我必须这样做吗?在 onCreateView 上
    • 确切地说,您可以按照@georkost 在onViewCreated 中所说的操作,也可以在 onCreateView 中完成。完全删除onStart 方法。更多信息请参见stackoverflow.com/a/38718205/1133011
    【解决方案2】:

    正如@georkost 所说,在 onViewCreated 中声明您的按钮引用,但从您的视图中调用 findViewById 方法:

    val button = view.findViewById<Button>(R.id.play)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      • 2022-10-07
      • 2020-04-18
      • 1970-01-01
      相关资源
      最近更新 更多