Android 点击 FAB 按钮打开另一个 fragment

文章目录

    使用 Android Studio 的 Basic Activity 模板创建了新项目。

    Basic Activity 内置了:

    • 一个底部 FAB 按钮
    • 两个 fragment 可以相互切换

    但是,我想实现的交互效果是: 点击 FAB 按钮,由第一个 fragment 切换到第二个。

    实现代码

    第一个 fragment 的 onViewCreated 尾部添加

    activity?.findViewById<FloatingActionButton>(R.id.fab)?.apply {
    	show()
    	setOnClickListener {
    		findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
    	}
    }
    

    这里凸显了 kotlin 的 apply 语法的方便之处。

    第二个 fragment 的 onViewCreated 尾部添加

    activity?.findViewById<FloatingActionButton>(R.id.fab)?.hide()
    

    一些学习笔记:

    fragment 中获取当前 activity

    activity 即是当前 fragment 所属的 activity。getActivity() 的文档:

    androidx.fragment.app.Fragment @Nullable

    public final androidx.fragment.app.FragmentActivity getActivity()

    Return the FragmentActivity this fragment is currently associated with. May return null if the fragment is associated with a Context instead.

    第二个 fragment 需要隐藏 fab 的原因

    如果不隐藏,点击 FAB 会报错

    java.lang.IllegalArgumentException: navigation destination com.sunzhongwei.todo:id/action_FirstFragment_to_SecondFragment is unknown to this NavController

    main activity 中的失败尝试

    Main Activity 的 onCreate 中添加

    Navigation.findNavController(this,R.id.nav_graph)
    	.navigate(R.id.action_FirstFragment_to_SecondFragment);
    
    报错:
    
    java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
    

    Main Activity 的 onStart 中添加

    override fun onStart() {
    	super.onStart()
    	findViewById<FloatingActionButton>(R.id.fab).setOnClickListener {
    		it.findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
    	}
    }
    
    报错:
    
    java.lang.IllegalStateException: View com.google.android.material.floatingactionbutton.FloatingActionButton does not have a NavController set
    

    onCreate

    val navController = findNavController(R.id.nav_host_fragment)
    findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view ->
    	navController.navigate(R.id.action_FirstFragment_to_SecondFragment);
    }
    
    报错:
    
    java.lang.IllegalArgumentException: navigation destination com.sunzhongwei.todo:id/action_FirstFragment_to_SecondFragment is unknown to this NavController
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式