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跳转。

相关推荐
Ccuno几秒前
Java中常用的数据结构实现类概念
java·开发语言·深度学习
leaves falling5 分钟前
c语言-数1到100的所有整数中数字9出行的个数
c语言·开发语言·算法
鹏多多8 分钟前
Flutter下拉刷新上拉加载侧拉刷新插件:easy_refresh全面使用指南
android·前端·ios
3824278279 分钟前
python3网络爬虫开发实战 第2版:并发限制
开发语言·爬虫·python
studyForMokey11 分钟前
【Android Gradle】Gradle系列
android
ss27316 分钟前
线程池配置-七大关键参数
java·开发语言
HeDongDong-17 分钟前
Kotlin Lambda 表达式详解
android·开发语言·kotlin
最后一个bug19 分钟前
浅显易懂的讲解MMU是如何使用4级页表把虚拟地址转化为物理地址的~
linux·服务器·开发语言·系统架构·计算机外设
superman超哥20 分钟前
Rust 函数定义与参数传递:所有权系统下的设计艺术
开发语言·rust·设计艺术·rust函数定义·rust参数传递
2301_7890156220 分钟前
C++:set/multiset和map/multimap文档详细解析
c语言·开发语言·c++·vscode·排序算法·set·map