[英]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.