Android: why must use getBaseContext() instead of

2019-01-07 05:30发布

this often to reference to current context. But, at some case, why we must use getBaseContext() instead of this. (It means when use this will notice error).

Here is my example:

Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);            
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?>arg0, View arg1, int arg2, long arg3){
       Toast.makeText(getBaseContext(),"SELECTED", Toast.LENGTH_SHORT).show(); //this line
    }

At above code, when I change getBaseContext() to this will receive error.

Who can explain for me, please.

7条回答
▲ chillily
2楼-- · 2019-01-07 05:59

If this code is in the Activity MyActivity, you could also replace getBaseContext() by MyActivity.this.

This is because this refers to the OnItemSelectedListener instance, not to the Activity. getBaseContext() refers to the Activity context.

查看更多
登录 后发表回答