14

我有一个名为BinderDataextends的类BaseAdapter。我想获得基类上下文。我尝试使用getContext(),但在BaseAdapter.

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

4

3 回答 3

32

另一种解决方案-

如果您有父母,则可以像这样直接访问上下文-

 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;
            }

    }
于 2014-02-20T08:39:35.377 回答
15

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

public class SampleAdapter extends BaseAdapter {
    private Context context;

    public SampleAdapter(Context context) {
        this.context = context;
    }

    /* ... other methods ... */
}
于 2013-05-16T18:15:44.497 回答
4
Context context = parent.getContext();
于 2014-06-14T05:21:16.440 回答