Kotlin Fragment 按钮跳转报错解决:Unresolved reference ‘floatingActionButton‘

报错场景

在使用Kotlin开发时,为了实现从listfragment通过一个按钮跳转到addfragment时,按照教程

复制代码
class ListFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_list, container, false)

   
        view.floatingActionButton.setOnClickListener{
            findNavController().navigate(R.id.action_listFragment_to_addFragment)
        }
        return view
    }

然而报错,> Task :app:compileDebugKotlin e: file:///D:/android_projects/ToDoApp/app/src/main/java/com/example/todoapp/ListFragment.kt:20:14 Unresolved reference 'floatingActionButton'. > Task :app:compileDebugKotlin FAILED。

报错原因:在 Fragment 中直接通过 view.floatingActionButton 获取控件失败 ------Kotlin 不会自动为布局中的控件生成 "直接引用"(需配合 viewBindingfindViewById 显式绑定),所以编译器找不到 floatingActionButton 这个变量。

解决方法:

使用 findViewById(无需配置,快速临时解决)

复制代码
class ListFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_list, container, false)

        val fab = view.findViewById<FloatingActionButton>(R.id.floatingActionButton)
        fab.setOnClickListener {
            findNavController().navigate(R.id.action_listFragment_to_addFragment)
        }
        return view
    }
}

根据提示

复制代码
import com.google.android.material.floatingactionbutton.FloatingActionButton

完成,此时点击按钮实现fragment跳转。

相关推荐
shandianchengzi8 分钟前
【科普】安卓|安卓手机上如何简便实现Ctrl+Z(需要键盘或一台Windows电脑)
android·windows·智能手机·计算机外设·安卓·科普·记录
赏金术士8 小时前
Compose 教学项目
android·kotlin·compose
晓梦林8 小时前
ximai靶场学习笔记
android·笔记·学习
kkeeper~8 小时前
0基础C语言积跬步之深入理解指针(5下)
c语言·开发语言
一直不明飞行8 小时前
Java的equals(),hashCode()应该在什么时候重写
java·开发语言·jvm
盲敲代码的阿豪9 小时前
Python 入门基础教程(爬虫前置版)
开发语言·爬虫·python
basketball6169 小时前
C++ 构造函数完全指南:从入门到进阶
java·开发语言·c++
互联科技报9 小时前
2026超融合选型:Top5品牌与市场格局解读
开发语言·perl
weixin199701080169 小时前
[特殊字符] 智能数据采集:数字化转型的“数据石油勘探队”(附Python实战源码)
开发语言·python
想唱rap10 小时前
IO多路转接之poll
服务器·开发语言·数据库·c++