【问题标题】:How to get context for BaseAdapter in Android如何在 Android 中获取 BaseAdapter 的上下文
【发布时间】:2013-05-11 18:24:09
【问题描述】:

我有一个名为BinderData 的类,它扩展了BaseAdapter。我想获得基类上下文。我尝试使用getContext(),但在BaseAdapter 的情况下不起作用。

我怎样才能得到这个类的上下文?

【问题讨论】:

    标签: android baseadapter android-context


    【解决方案1】:

    另一种解决方案-

    如果你有父母,你可以像这样直接访问上下文——

     public class SampleAdapter extends BaseAdapter {
    
                LayoutInflater inflater;
    
                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    if(inflater == null){
                    Context context = parent.getContext();
                    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    }
                    ...
                    ...
    
                    return convertView;
                }
    
        }
    

    【讨论】:

    • 这应该是正确的答案。 @Karakuri 的回答效率低下。
    • 你拯救了我的一天,上帝保佑你。这就像一个魅力
    【解决方案2】:

    创建一个将Context 作为其参数之一的构造函数,并将其存储在私有变量中。

    public class SampleAdapter extends BaseAdapter {
        private Context context;
    
        public SampleAdapter(Context context) {
            this.context = context;
        }
    
        /* ... other methods ... */
    }
    

    【讨论】:

    • 我建议您在开始专门处理 Android 之前牢牢掌握 Java 基础知识。
    • 将上下文设置为空。
    • 你传递它为空吗?你需要传递一个有效的上下文。
    • @Karakuri 嘿,我也将上下文设为空:(
    • 对于那些获得 Context null 检查您是如何创建适配器对象的。如果您从 Activity 的 onCreate 方法创建它,您可以简单地传递 getApplicationContext()this
    【解决方案3】:
    Context context = parent.getContext();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-29
      • 2018-11-18
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      相关资源
      最近更新 更多