【问题标题】:Context in a baseAdapter classbaseAdapter 类中的上下文
【发布时间】:2013-03-04 10:22:10
【问题描述】:
有没有办法通过getApplicationContext() 在BaseAdapter 类中获取context?
我需要这个,因为我要从 url 加载图像。这里我使用context:
这是在扩展BaseAdapter的类中
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
【问题讨论】:
标签:
android
baseadapter
android-context
【解决方案1】:
在扩展/实现时将其传递给构造函数:
public class MyAdapter extends SomeBaseAdapter{
private final Context mcontext;
public MyAdapter(Context c){
mContext = c;
}
}
【解决方案2】:
您可以在适配器构造函数中传递对 Context 的引用并将其存储,也可以在方法 getView() 中直接从父级引用它
public class ToDoListAdapter extends BaseAdapter {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//inflate layout
}
}
【解决方案3】:
你可以尝试实例化一个变量来带来这样的上下文内容:
在 getView()
视图视图 = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemtutor, null);
并创建一个上下文变量:
上下文 mycontext = view.getContext();