Android fragments 为什么可以';我找到了包含在片段';什么样的布局?

Android fragments 为什么可以';我找到了包含在片段';什么样的布局?,android-fragments,kotlin,Android Fragments,Kotlin,我在xml中包含一个片段的布局。在片段的Kotlin代码中,我想访问布局中的一个按钮,以便设置其onClick侦听器。但是,尝试按id查找按钮会导致应用程序关闭。(我使用底部导航导航到片段,应用程序刚刚关闭。没有错误消息。)通过id查找布局本身是成功的,因为将其作为字符串记录会给出“androidx.constraintlayout.widget.constraintlayout…”,这是我包含的布局的父标记 这是我的代码,简化版: 包含的布局,noteView.xml: ... &

我在xml中包含一个片段的布局。在片段的Kotlin代码中,我想访问布局中的一个按钮,以便设置其onClick侦听器。但是,尝试按id查找按钮会导致应用程序关闭。(我使用底部导航导航到片段,应用程序刚刚关闭。没有错误消息。)通过id查找布局本身是成功的,因为将其作为字符串记录会给出“androidx.constraintlayout.widget.constraintlayout…”,这是我包含的布局的父标记

这是我的代码,简化版:

包含的布局,noteView.xml:

   ...
   <androidx.constraintlayout.widget.ConstraintLayout 
    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:id="@+id/noteViewCont">

    <ImageButton
        android:id="@+id/button"/>
    ...
我提到了这个问题,并尝试了其中提出的各种解决方案: 没有一个奏效。 -如您所见,包含的XML文件的id与包含(noteViewCont)的id相同。 -我尝试在onViewCreated()中设置noteVw,但没有任何改变

谢谢大家!

更新

-我尝试了一个基本上完全绕过noteVw的建议,并执行
root.findviewbyd(R.id.button)
,但这并没有改变什么```

此外,以下是我尝试创建的onViewCreated:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val noteVw: View = view.findViewById(R.id.noteViewCont)
        val makeBtn: Button = noteVw.findViewById(R.id.button)
    }
第二次更新

多亏了@CôngH,我明白了ả我有一次他问我崩溃日志,我意识到在我不停地说应用程序“没有错误信息”之前,我可能应该检查一下我是否得到了一个崩溃日志。所以,我找到了这篇文章 在我的事故日志中发现了:

05-04 01:17:43.758   551   551 E AndroidRuntime: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button
我在这篇文章中没有提到的一个细节是,我实际上在试图存储在
val-button:button
中的视图中使用了一个ImageButton。我把按钮换成了ImageButton,一切正常。 还有,第一个变化是@CôngHả我建议这是一个简化代码的好方法。可以直接从包含布局的布局访问包含布局的子级。我删除了noteVw,只使用root.findviewbyd来获取按钮。
很抱歉提出一个明显的问题,但我希望这是一个有用的示例。

在XML中定义
ImageButton
,但在代码中将其转换为Button,而不是Button的实例,改为

val makeBtn: ImageButton = noteVw.findViewById(R.id.button)

您是否尝试将
noteVw.findViewById(R.id.button)
更改为
root.findViewById(R.id.button)
?@CôngHải、 我现在刚试过,但应用程序仍然关闭,没有任何解释。不过,谢谢你!给我看日志crash@CôngHải、 谢谢大家!!我一直没注意到!当我编辑我的post.hmm更改为val makeBtn:ImageButton=noteVw.findViewById(R.id.button)时,请查看我的第二次更新。它将起作用
05-04 01:17:43.758   551   551 E AndroidRuntime: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button
val makeBtn: ImageButton = noteVw.findViewById(R.id.button)