标签:style blog http color io 使用 ar java strong
问: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中的方法。
参考:http://ask.csdn.net/questions/942
为什么要用getBaseContext()方法代替this?(转)
标签:style blog http color io 使用 ar java strong
原文地址:http://www.cnblogs.com/smilefortoday/p/4021861.html