[英]What does context refer to in the code below?
这是一个简单的画廊程序。 我已将代码缩减为回答问题所需的必要部分。 我的问题是为什么上下文没有初始化,然后如何知道下面代码中的上下文引用是什么?
public class GalleryActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
myImageView.setImageResource(imageIDs[position]);
}
});
}
public class ImageAdapter extends BaseAdapter
{
Context context;
public ImageAdapter(Context c)
{
context = c;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
return imageView;
}
}
}
context
未初始化,因为当您实例化ImageAdapter
类时,您必须设置context
,例如:
ImageAdapter myImageAdapter = new ImageAdapter(getApplicationContext());
然后在ImageAdapter
类中,您将使用context
变量:
ImageView imageView = new ImageView(context);
在您的代码中,您有:
new ImageAdapter(this);
this
指的是当前类 GalleryActivity。 GalleryActivity是一个Activity, Activity是Context的子类。 因此,您正在使用上下文调用 ImageAdapter 构造函数。 然后,在您的构造函数中,您存储对该 Context 的引用, context = c
。 实际上, context
现在指向一个 Context,它是一个 Activity。
不需要显式实例化Context,因为Android系统已经给了你一个有效的Activity实例,而且由于Activity是一种Context,你就有了一个有效的Context。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.