How to get context for BaseAdapter in Android

末鹿安然 提交于 2019-11-30 08:06:00

问题


I have a class named BinderData which extends BaseAdapter. I want to get the base class context. I tried to use getContext() but that doesn't work in case of BaseAdapter.

How can I get the Context of this class?


回答1:


One more solution-

If you have a parent, you can directly access the context like 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;
            }

    }



回答2:


Make a constructor that takes a Context as one of its arguments and store it in a private variable.

public class SampleAdapter extends BaseAdapter {
    private Context context;

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

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



回答3:


Context context = parent.getContext();


来源:https://stackoverflow.com/questions/16594557/how-to-get-context-for-baseadapter-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!