如何在Android中获取BaseAdapter的上下文

时间:2013-05-16 18:13:01

标签: android baseadapter android-context

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

如何获得此课程的上下文?

3 个答案:

答案 0 :(得分:27)

另一个解决方案 -

如果你有父母,你可以直接访问上下文,如so-

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

    }

答案 1 :(得分:15)

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

public class SampleAdapter extends BaseAdapter {
    private Context context;

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

    /* ... other methods ... */
}

答案 2 :(得分:4)

Context context = parent.getContext();