将自定义布局添加到标准工具栏

时间:2021-03-29 18:45:33

标签: android android-actionbar toolbar android-toolbar

我想将我的自定义布局添加到现有工具栏的一侧,保留 NavigationUI 的所有功能(向上按钮、动画、放置按钮和抽屉等)

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

经过一番研究,我找到了解决方案


MainActivity.kt

class MainActivity : AppCompatActivity() {

    private val navController by lazy { findNavController(R.id.main_nav_host_fragment) }
    private val appBarConfiguration by lazy { AppBarConfiguration(navController.graph) }

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val navController = this.findNavController(R.id.main_nav_host_fragment)
        NavigationUI.setupActionBarWithNavController(this, navController)
        NavigationUI.setupWithNavController(
            findViewById<NavigationView>(R.id.navigation_view),
            navController
        )
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = this.findNavController(R.id.main_nav_host_fragment)
        return NavigationUI.navigateUp(navController, appBarConfiguration)
    }
}


FragmentToolbar.kt 界面

interface FragmentToolbar {
    fun clearActionBar()
    fun setCustomActionBar()
}


MainFragment.kt
下一个类 MainFragment.kt 是抽象的,方法 clearActionBar()setCustomActionBar() 可以被覆盖。它们在 FragmentToolbar.kt 界面中定义,因为如果您在第一个片段中设置自定义布局,您也会在所有其他片段中看到它。所以,你几乎总是需要清除你的 ActionBar 并且这个类负责标准实现。 setCustomActionBar() 由您决定\

abstract class MainFragment : Fragment(), FragmentToolbar {

val actionBar: ActionBar? by lazy { (requireActivity() as AppCompatActivity).supportActionBar }

override fun clearActionBar() {
    actionBar?.apply {
        setDisplayShowCustomEnabled(false)
        setDisplayShowTitleEnabled(true)
    }
}

override fun setCustomActionBar() {}

}


MyFragment.kt

class MyFragment : MainFragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        clearActionBar() // defined in MainFragment

        // Your code
    }

    override fun setCustomActionBar() {
        actionBar?.apply {
            setDisplayShowCustomEnabled(true)
            setCustomView(R.layout.view_cart_and_bill)
        }

        actionBar?.customView?.apply { /* Here use findViewById to find necessary views inside your custom layout */ }
    }
}

希望我的回答对你有帮助。如果 ViewBinding 可以与在运行时添加的此布局一起使用,那就太好了,但我还没有解决这个问题

相关问题