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.
If this code is in the Activity
MyActivity
, you could also replacegetBaseContext()
byMyActivity.this
.This is because
this
refers to the OnItemSelectedListener instance, not to the Activity.getBaseContext()
refers to the Activity context.