英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论