如何仅使用Android导航体系结构组件在一个子片段上添加选项项目?

问题描述 投票:0回答:1

我正在将导航体系结构组件与androidx一起使用。

我只想在我的一个子片段上的导航栏右侧添加一个菜单图标。

有可能吗?我想念什么?这是我的第一个测试代码实现:

my_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/optionIconId"
        android:icon="@drawable/option_icon"
        android:visible="true"
        app:showAsAction="ifRoom|withText"/>
</menu>

TestFragment.kt

class TestFragment : Fragment() {

    /**
     * Fragment binding.
     */
    private var _binding: FragmentTestBinding? = null

    /**
     * Fragment binding.
     */
    private val binding get() = this._binding!!

    /**
     * @inheritdocs
     */
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        this._binding = FragmentTestBinding.inflate(inflater, container, false)
        return this.binding.root
    }

    /**
     * @inheritdocs
     */
    override fun onPrepareOptionsMenu(menu: Menu) {
        menu.findItem(R.id.optionIconId).isVisible = true
        super.onPrepareOptionsMenu(menu)
    }

    /**
     * @inheritdocs
     */
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.optionIconId -> {
                println("CLICK CLICK CLICK")
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}

fragment_test.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="test"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
android kotlin navigation androidx appbar
1个回答
0
投票

您可以从您当前的片段或活动中管理此行为。您需要为所有片段(在您的活动中)创建一个工具栏,并通过导航更改的回调在那里管理菜单的可见性,或者为每个具有不同菜单的片段创建工具栏。

© www.soinside.com 2019 - 2024. All rights reserved.