我正在处理一个包含两个片段的简单活动。两个片段都有searchView作为菜单项。问题是,如果我在第一个片段中展开搜索视图,在第二个片段中展开搜索视图,反之亦然;我不想要的。
碎片是
class TitleScreen : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_title_screen, container, false)
setHasOptionsMenu(true)
view.findViewById<Button>(R.id.play_btn).setOnClickListener {
Navigation.findNavController(view).navigate(R.id.action_title_screen_to_register)
}
return view
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.search, menu)
super.onCreateOptionsMenu(menu, inflater)
}
}
class Register : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_register, container, false)
setHasOptionsMenu(true)
view.findViewById<Button>(R.id.signup_btn).setOnClickListener {
Navigation.findNavController(view).navigate(R.id.action_register_to_match)
}
return view
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.search, menu)
super.onCreateOptionsMenu(menu, inflater)
}
}
菜单是
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:icon="@drawable/ic_search_24px"
android:title="search"
app:showAsAction="always|collapseActionView" />
</menu>
导航是
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
app:startDestination="@+id/title_screen">
<fragment
android:id="@+id/title_screen"
android:name="com.example.android.navigationsample.TitleScreen"
android:label="fragment_title_screen"
tools:layout="@layout/fragment_title_screen">
<action
android:id="@+id/action_title_screen_to_register"
app:destination="@id/register"
app:popEnterAnim="@anim/slide_in_left"
app:popExitAnim="@anim/slide_out_right"
app:enterAnim="@anim/slide_in_right"
app:exitAnim="@anim/slide_out_left"/>
</fragment>
<fragment
android:id="@+id/register"
android:name="com.example.android.navigationsample.Register"
android:label="fragment_register"
tools:layout="@layout/fragment_register"/>
</navigation>
如何在下一个片段中保持菜单折叠?预先感谢。
答案 0 :(得分:1)
使用其他android:id
。菜单系统不知道哪个片段给出了哪个MenuItem
,因此它所看到的只是相同的MenuItem,因此可以正确地保持其状态。对不同的片段使用不同的android:id
意味着菜单将它们视为具有单独的折叠/展开状态的单独菜单项。