我有一个小应用程序,我有一个片段AchievementFragment
,在那里我有几个imageButton
s。我想让它,当我点击其中一个,吐司出现在屏幕上,但我有一个问题,只是imageButton
本身。我试着遵循一些在线教程,像这个:https://www.geeksforgeeks.org/imagebutton-in-kotlin/,但当我试图使用
val imgbtn = findViewById<ImageButton>(R.id.imageBtn)
我得到未解析的findViewById引用错误。
你不能在片段中直接使用findViewById,你必须在根视图中使用它,在你的onCreateView中你返回根视图。其他视图在根视图中。如果你想访问根目录下的视图你应该在返回根视图
之前使用这样的命令override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_blank, container, false)
val imgbtn = root.findViewById<ImageButton>(R.id.imageBtn)
return root
}
val imgbtn = (activity as ActivityName).findViewById<ImageButton>(R.id.imageBtn)
将ActivityName替换为您的活动名称。
或
使用View Binding代替findViewById。https://developer.android.com/topic/libraries/view-binding