zoukankan      html  css  js  c++  java
  • 为什么要用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中的方法。

    参考:http://ask.csdn.net/questions/942

  • 相关阅读:
    servlet验证账号密码
    servlet概述
    JAVA WEB开发环境与搭建
    JavaScript简介
    css样式简介
    html简介
    西柚电子邮箱登录页面
    西南石油大学计科院主页
    PHP 简单分页 献给小白
    安装FastDFS
  • 原文地址:https://www.cnblogs.com/smilefortoday/p/4021861.html
Copyright © 2011-2022 走看看