我正在学习如何以新程序员的身份实现Navigation Drawer,当时我正在研究Google Codelab提供的代码,并遇到了“ this”(提供的代码)。 我想知道它到底指的是什么。
我已经尝试过用“ this”代替我想到的任何东西,但无法解决。
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
if (drawer != null) {
drawer.addDrawerListener(toggle);
}
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
if (navigationView != null) {
navigationView.setNavigationItemSelectedListener(this);
}
答案 0 :(得分:2)
NavigationView有一个称为:
的方法。setNavigationItemSelectedListener(NavigationView.OnNavigationItemSelectedListener listener)
这意味着您需要在调用该方法时提供一种类型为“ OnNavigationItemListener”的参数。
有两种方法可以提供此参数。
您的问题与第二种方法有关
例如
//notice now myCustomClass is implemented as a type of "OnNavigationItemSelectedListener" (the implements keyword)
//according to https://developer.android.com/reference/android/support/design/widget/NavigationView.OnNavigationItemSelectedListener.html
//all implementation of OnNavigationItemSelectedListener requires
//a method called "onNavigationItemSelected" -> so we add that in too.
public MyCustomClass implements NavigationView.OnNavigationItemSelectedListener{
public void someMethods(){
//...setting the argument to "this", means when the navigation item is selected,
//the method onNavigationItemSelected in "MyCustomClass" will be called
navigationView.setNavigationItemSelectedListener(this);
}
//this method will be called whenever navigationItem is selected
boolean onNavigationItemSelected(MenuItem item){
//you will do your coding on what to do when an navigationItem is selected here.
}
}
请参阅https://www.w3schools.com/java/ref_keyword_implements.asp,以获取有关Implements关键字的更多信息。
答案 1 :(得分:0)
如果包含此代码的活动或片段或类实现了this
,则可以传递NavigationView.OnNavigationItemSelectedListener
。
此处是NavigationView和NavigationView.OnNavigationItemSelectedListener,以获取更多详细信息。
有帮助吗?