我有一個GridView與3列和3行我想改變圖像,當用戶點擊任何兩個圖像。如何更改Gridview運行時的圖像?
比如我點擊第一行1和列3圖像和第二,我點擊行3和列2顯示現在我想改變這兩個圖像類似交換的形象怎麼可能?
public class MainActivity extends Activity {
/** Called when the activity is first created. */
GridView gridView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView = (GridView)findViewById(R.id.gridviewmy);
gridView.setAdapter(new ImageAdapter(this));
final ImageAdapter im = new ImageAdapter(this);
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int i=0; int j=0;
if(i != 0){
j=arg2;
System.out.println("First Click "+j);
}else{
i=arg2;
System.out.println("Second Click "+i);
}
im.getItem(arg2);
//im.changeImage();
Toast.makeText(MainActivity.this, ""+arg2, Toast.LENGTH_SHORT).show();
System.out.println("AdapterView "+arg0);
System.out.println("View "+arg1);
System.out.println("Integer "+arg2);
System.out.println("long "+arg3);
}
});
}
}
class ImageAdapter extends BaseAdapter{
private Context mContext;
ImageView iView;
public ImageAdapter(Context c){
this.mContext = c;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
System.out.println("Item Is :-"+mThumbIds[position].toString());
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
System.out.println("Geting Id of Item "+mThumbIds[position]);
if(iView != null){
iView.setImageResource(mThumbIds[0]);
Toast.makeText(mContext, "Call", Toast.LENGTH_SHORT).show();
}
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null){
iView = new ImageView(mContext);
iView.setLayoutParams(new GridView.LayoutParams(85, 85));
iView.setScaleType(ImageView.ScaleType.CENTER_CROP);
iView.setPadding(8,8,8,8);
}else{
iView = (ImageView)convertView;
}
iView.setImageResource(mThumbIds[position]);
return iView;
}
private Integer[] mThumbIds = {
R.drawable.a_bhaibij, R.drawable.a_dashera, R.drawable.a_dipawali,
R.drawable.a_gandhi, R.drawable.a_holi, R.drawable.a_indepe,
R.drawable.a_janmastmi, R.drawable.a_kite, R.drawable.a_newyear
};
public void changeImage(){
iView.setImageResource(mThumbIds[5]);
}
}
喜greak,謝謝,我有一個問題,我宣佈mThumbIds整數數組ImageAdapterclass當嘗試MainActivity當時收到錯誤,也notifyDataSetChanged(); geting錯誤怎麼解決呢? mainActivity中的 – 2011-06-02 11:36:35
使用im.notifyDataSetChanged();這裏im是ImageAdapter的對象 – 2011-06-02 12:02:48