如何将项目添加到Android Studio的导航抽屉模板并为其设置监听器?

huangapple go评论60阅读模式
英文:

How to add an item to Android Studio's Navigation Drawer template and set Listener for it?

问题

抱歉,您提供的内容已经是中文了,不需要翻译。如果您有其他需要处理的事项,请随时告诉我。

英文:

I cant find where is navigationView.setNavigationItemSelectedListener used in that sample.
I want to link that item to a fragment like what's done on the template!
Is there any other way to set setNavigationItemSelectedListener without overriding this method?

答案1

得分: 2

你在 onCreate 中使用了:

navigationView.setNavigationItemSelectedListener(this);

为了回答你的问题,我认为不是这样的。

你的 YourActivity 实现了 NavigationView.OnNavigationItemSelectedListener 接口:

YourActivity implements NavigationView.OnNavigationItemSelectedListener {...}

onCreate 内部:

// 处理抽屉逻辑
navigationView.setNavigationItemSelectedListener(this);

然后,在导航监听器中:

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    // 使用 item.getItemId 处理点击事件
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

同样在 OnBackPressed 中检查并关闭抽屉。我假设你知道如何加载你的片段。

至少在 Android Studio 4.0.1 中, 默认模板使用了 Navigation Component,该组件旨在替代你在问题中提到的实现以及我展示的实现。如果你想使用 Navigation Component,请参考此链接

英文:

You use

navigationView.setNavigationItemSelectedListener(this);

inside onCreate. And to answer your question I don't think so.

YourActivity implements NavigationView.OnNavigationItemSelectedListener {...}

Inside onCreate

//handle drawer logic

    navigationView.setNavigationItemSelectedListener(this);

Then the navigation listener

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        use item.getItemId to handle the clicks
drawer.closeDrawer(GravityCompat.START);
        return true;
    }

Check for and close the drawer in OnBackPressed as well. I'm assuming you know how to load your fragment.

The default template at least on Android Studio 4.0.1 uses Navigation Component, which is meant to replace the implementation you meant in your question and the one I showed. So If you want to use navigation component refer to this link

huangapple
  • 本文由 发表于 2020年9月30日 14:55:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64132352.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定