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

相关推荐
火柴就是我11 小时前
让我们实现一个更好看的内部阴影按钮
android·flutter
FunnySaltyFish15 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
砖厂小工18 小时前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心19 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心19 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
Kapaseker21 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴21 小时前
Android17 为什么重写 MessageQueue
android
阿巴斯甜2 天前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker2 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq95272 天前
Andorid Google 登录接入文档
android