工具栏菜单onOptionsItemSelected不适用于片段

时间:2020-04-23 19:25:59

标签: android android-toolbar android-architecture-navigation

当用户使用导航组件单击工具栏上的菜单时,我正在尝试更改当前片段,但是我根本无法从片段上使用菜单!我正在使用底部导航栏,其中包含2个片段,每个片段具有不同的工具栏菜单项,而不是使用导航抽屉。 这是HomeFragment.kt的一些片段:

override​ ​fun​ ​onCreateView​(
    inflater​:​ ​LayoutInflater​, ​container​:​ ​ViewGroup?​,
    savedInstanceState​:​ ​Bundle?​
)​:​ ​View?​ {
    activity?.title ​=​ getString(​R​.string.title_home)
    setHasOptionsMenu(​true​)

    return​ inflater.inflate(​R​.layout.fragment_home, container, ​false​)
}

override​ ​fun​ ​onCreateOptionsMenu​(​menu​:​ ​Menu​, ​inflater​:​ ​MenuInflater​) {
    inflater.inflate(​R​.menu.toolbar_menu, menu)
    super​ .onCreateOptionsMenu(menu, inflater)
}

override​ ​fun​ ​onOptionsItemSelected​(​item​:​ ​MenuItem​)​:​ ​Boolean​ {
    when​ (item.itemId) {
         R​.id.toolbar_about ​-​>​ {
            activity?.findNavController(​R​.id.bottom_nav_host)?.navigate(​R​.id.toAboutFragment)
             Toast​.makeText(context, ​"​You clicked on About menu​"​, ​Toast​.​LENGTH_SHORT​).show()
        }
        else​ ​-​>​ ​super​.onOptionsItemSelected(item)
    }
    return​ ​true​
}

它甚至不显示我指定的Toast。有人可以帮我吗?预先感谢!

3 个答案:

答案 0 :(得分:1)

您可以在主机“活动”上打开菜单。如果要在Fragment上打开它,则可以使用上下文。检查以下代码。

public class FragmentEditProfile extends Fragment {
    Context m_context;      //Context

    public static FragmentEditProfile newInstance() {
        return new FragmentEditProfile();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // Get context of host activity.
        m_context = getContext();
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View fragmentLayout = inflater.inflate(R.layout.fragment_profile_edit, container, false);

        // setNavigationOnClickListener of the host activity.
        ((MainActivity)m_context).toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Open the menu using context of host activity
                ((MainActivity) m_context).openDrawer();
            }
        });
        return fragmentLayout;
    }
}

如果您有任何疑问,请告诉我。希望会有所帮助。

答案 1 :(得分:0)

我设法通过直接从活动而不是片段中调用onOptionsItemSelected来解决此问题。所以我的最终代码如下:
HomeFragment.kt

//We set menu from fragment
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { 
    inflater.inflate(R.menu.toolbar_menu, menu)
    super .onCreateOptionsMenu(menu, inflater) 
}

MainActivity.kt

override fun onOptionsItemSelected(item: MenuItem): Boolean { 
    val navHost = findNavController(R.id.bottom_nav_host) 
    when (item.itemId) { 
        android.R.id.home -> { 
            onBackPressed() 
            return true 
        }
        //This one is for our fragment toolbar menu
        R.id.toolbar_about -> { 
            navHost.navigate(R.id.toAboutFragment) 
            return true 
        }
    }
    return false
}

答案 2 :(得分:0)

可能要检查的几件事

1)样式应用主题

<resources>
<style name="AppThem
parent="Theme.AppCompat.Light.DarkActionBar"> ..... 
  1. MainActivity 关注这一点
  • setupBottomNavigationBar() controller.observe(this,Observer {navController-> setupActionBarWithNavController(navController)}) currentNavController =控制器

除非将主活动设置为支持片段中的操作栏,否则片段代码将不起作用。我花了一段时间才明白这一点。...

    class MainActivity : AppCompatActivity() {
    private var currentNavController: LiveData<NavController>? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    if (savedInstanceState == null) {
            setupBottomNavigationBar()}
    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
    setupBottomNavigationBar()
    }


    private fun setupBottomNavigationBar() {
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)
        val navGraphIds = listOf(R.navigation.signin, R.navigation.register, R.navigation.elections_list)

        val controller = bottomNavigationView.setupWithNavController(
            navGraphIds = navGraphIds,
            fragmentManager = supportFragmentManager,
            containerId = R.id.nav_host_container,
            intent = intent
        )     
       controller.observe(this, Observer { navController ->
           setupActionBarWithNavController(navController) })
        currentNavController = controller
    }
    override fun onSupportNavigateUp(): Boolean {
        return currentNavController?.value?.navigateUp() ?: false
    }
  companion object
    }
  1. 在菜单/菜单集合中。这只是一个工作示例。 https://www.youtube.com/watch?v=DMkzIOLppf4和生产中通过流中编码
  2. 引用了很多内容

菜单代码

<menu
     android:id="@+id/menu_collections_new"
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/men_item1"
        android:icon="@drawable/ic_icon"
        android:title="item1"
        app:showAsAction="ifRoom"/>
        <item android:id="@+id/men_item2"
            app:showAsAction="never"
            android:title="item2"
            />
        <item android:id="@+id/men_item3"
            android:title="item3"
            app:showAsAction="never">
        <menu>
        <item
         android:id="@+id/subitem1"
        android:title="Subitem1"/>
        <item
            android:id="@+id/subitem2"
            android:title="Subitem2"/>
        </menu>
        </item>
        </menu>
  1. 片段代码 在实际的片段 FragmentOne.kt 中设置正确的代码 注意 super.onCreateOptionsMenu(菜单,充气机) inflater.inflate(R.menu.menu_collections_new,菜单)

    重写乐趣onCreate(savedInstanceState:Bundle?){ setHasOptionsMenu(true) super.onCreate(savedInstanceState) }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
     inflater.inflate(R.menu.menu_collections_new, menu)
     super.onCreateOptionsMenu(menu, inflater)
     }
    
     override fun onOptionsItemSelected(item: MenuItem): Boolean {
    
         when (item.itemId) {
             R.id.men_item1-> onSignOutClicked( "item1")
             R.id.men_item2 -> onSignOutClicked("item2")
             R.id.men_item3 ->onSignOutClicked("item3")
         }
         return super.onOptionsItemSelected(item)
    
    
         private fun onSignOutClicked(description:String) {
         Log.d(TAG,"dja 193 options menu selected $description")
         }