繁体   English   中英

setNavigationItemSelectedListener(this) 中的“this”指的是什么

[英]What does “this” refer to in setNavigationItemSelectedListener(this)

我正在学习如何以新程序员的身份实现导航抽屉,我正在检查 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);
}

NavigationView 有一个方法叫做:

setNavigationItemSelectedListener(NavigationView.OnNavigationItemSelectedListener listener)

https://developer.android.com/reference/android/support/design/widget/NavigationView#setnavigationitemselectedlistener

这意味着您需要在调用该方法时提供一个“OnNavigationItemListener”类型的参数。

有两种方法可以提供这个论点。

  1. 第一种方法是定义匿名 class (或方法参考,或 lambda 等)
  2. 第二种方法是实现对调用此方法的 class 的侦听器,然后将“this”作为参数传入。

您的问题与第二种方法有关

例如

//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.
    }

} 

有关 implements 关键字的更多信息,请参阅https://www.w3schools.com/java/ref_keyword_implements.asp

如果您的活动或片段或包含此代码的 class 实现NavigationView.OnNavigationItemSelectedListener ,则可以传递this

这是NavigationViewNavigationView.OnNavigationItemSelectedListener了解更多详细信息。

这有帮助吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM