首页 > 其他 > 详细

为什么要用getBaseContext()方法代替this?(转)

时间:2014-10-13 12:28:40      阅读:195      评论:0      收藏:0      [点我收藏+]

问: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?(转)

原文:http://www.cnblogs.com/smilefortoday/p/4021861.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!