2012-06-23 38 views
0

我想跟着建立一個GridView佈局的教程,但是我看到上下文被傳遞給圖像適配器,我不想複製代碼或只是重新鍵入它不知道爲什麼它被做,所以我想知道爲什麼它被傳遞。我基本瞭解它是關於應用程序或其環境的信息。爲什麼imageView需要將上下文傳遞給它?

import android.content.Context; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.GridView; 
import android.widget.ImageView; 

public class ImageAdapter extends BaseAdapter { 
private Context mContext; 

// Keep all Images in array 
public Integer[] mThumbIds = { 
     R.drawable.pic_1, R.drawable.pic_2, 
     R.drawable.pic_3, R.drawable.pic_4, 
     R.drawable.pic_5, R.drawable.pic_6, 
     R.drawable.pic_7, R.drawable.pic_8, 
     R.drawable.pic_9, R.drawable.pic_10, 
     R.drawable.pic_11, R.drawable.pic_12, 
     R.drawable.pic_13, R.drawable.pic_14, 
     R.drawable.pic_15 
}; 

// Constructor 
public ImageAdapter(Context c){ 
    mContext = c; 
} 

@Override 
public int getCount() { 
    return mThumbIds.length; 
} 

@Override 
public Object getItem(int position) { 
    return mThumbIds[position]; 
} 

@Override 
public long getItemId(int position) { 
    return 0; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView imageView = new ImageView(mContext); 
    imageView.setImageResource(mThumbIds[position]); 
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
    imageView.setLayoutParams(new GridView.LayoutParams(70, 70)); 
    return imageView; 
} 

} 

回答

0

的ImageAdapter存儲在其mContext構造的背景下,由於ImageView的構造函數需要它自己的構造之後。與所有視圖一樣,ImageView需要一個上下文,通過該上下文可以訪問當前主題,資源等。

0

檢查此鏈接以獲取更多信息Context Info瞭解詳細信息爲什麼它用於不同的目的也檢查此如果要tp請參閱上下文類別Context Class

相關問題