我想用一些图片显示gridview。我成功地在gridview中显示图像,但是当我想单击图像以便在Toast中显示文本时,它什么都没发生。 这是我的示例代码。
GridView gridView = (GridView)layout.findViewById(R.id.emoticons_grid);
gridView.setAdapter(new EmoticonsGridAdapter(getApplicationContext()));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(MainActivity.this, ""+position,Toast.LENGTH_SHORT).show();}
然后是适配器。
public EmoticonsGridAdapter(Context c)
{ context = c;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return imageIDs.length; }
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return imageIDs[position];
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@SuppressLint("UseValueOf")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(80, 80));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(imageIDs[position]);
return imageView;
}
private Integer[] imageIDs = {
R.drawable.emo1,
R.drawable.emo2,
R.drawable.emo3,
R.drawable.emo4,
R.drawable.emo5,
R.drawable.emo6,
R.drawable.emo7,
R.drawable.emo8,
R.drawable.emo9,
R.drawable.emo10,
R.drawable.emo12,
R.drawable.emo13,
R.drawable.emo14,
R.drawable.emo15,
R.drawable.emo16,
R.drawable.emo17,
R.drawable.emo18,
R.drawable.emo19,
R.drawable.emo20
};
你介意解释什么是错的吗?