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

Sid*_*Sid 13 android android-context baseadapter

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

我怎样才能获得这堂课的背景?

My *_*God 30

一个解决方案 -

如果您有父母,您可以直接访问上下文,如此

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

    }
Run Code Online (Sandbox Code Playgroud)

  • 这应该是正确的答案.@ Karakuri的答案是低效的. (4认同)

Kar*_*uri 15

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

public class SampleAdapter extends BaseAdapter {
    private Context context;

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

    /* ... other methods ... */
}
Run Code Online (Sandbox Code Playgroud)

  • 我建议你在开始专门处理Android之前,先掌握Java基础知识. (2认同)

Aja*_*dya 6

Context context = parent.getContext();
Run Code Online (Sandbox Code Playgroud)