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

  • 相关阅读:
    MIUI(Android)使用Webview上传文件
    使用EntityFramework中DbSet.Set(Type entityType)方法碰到的问题
    Web文件管理:elFinder.Net(支持FTP)
    ASP.NET 根据现有动态页面生成静态Html
    LaTeX学习
    Java Integer剖析
    20140711 loop
    20140711 eat
    20140711 set
    20140710 loop
  • 原文地址:https://www.cnblogs.com/smilefortoday/p/4021861.html
Copyright © 2011-2022 走看看