为什么要用getBaseContext()方法代替this?(转)
问:this 常常引用当前的 context。但是有些时候,必须使用getBaseContext()来代替this。就是说使用this会引发错误。
如下面的例子:
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
}
当我把getBaseContext()变成this就会有错误。
为什么这种情况下必须使用getBaseContext()方法,而不能使用this呢?
答:
1.getApplicationContext ()方法在应用程序要被摧毁时,返回整个应用程序生命周期的应用上下文。
2.this应用上下文返回activity的当前上下文,属于activity。当它被摧毁时,activity也被摧毁。但是在你的事例中它是指Spinner实例,因为我们在onItemSelected(AdapterView<?>arg0, View arg1, int arg2, long arg3)方法中使用它。这个方法是来自Spinner类,而Spinner从AdapterView.OnItemSelectedListener接口中继承这个方法。
3.getBaseContext()是 ContextWrapper中的方法。
我是刚刚进入公司的Android实习生,菜鸟一枚,博客记录我犯过的错,收获的东西,学到的知识和技术,可能里面会有很多错误的地方,幼稚的地方,欢迎大家指出来,帮助我进步,但请别伤害我,我只是菜鸟一枚,我在努力争取进步。

浙公网安备 33010602011771号