我正在尝试使用 gridView 创建一个 android 应用程序。在此应用程序中,我尝试将图像随机添加到 GridView 中。我有 5 张图像,这些图像添加到了可绘制对象中,例如 R.drawable.c0、R.drawable.c1、R.drawable.c2、R.drawable.c3、R.drawable.c4。
当我们单击每个网格时,每个网格中的图像会随机更改。我的编码工作正常,可以在每个网格单击中随机更改图像。但是我需要帮助来获取图像名称。
public class MainActivity extends Activity {
GridView gridview;
ImageView imageView ;
public static Integer[] mThumbIds = {
R.drawable.c0, R.drawable.c1,
R.drawable.c2, R.drawable.c3,
R.drawable.c4,
R.drawable.c0, R.drawable.c1,
R.drawable.c2, R.drawable.c3,
R.drawable.c4,
R.drawable.c0, R.drawable.c1,
R.drawable.c2, R.drawable.c3,
R.drawable.c4,
R.drawable.c0, R.drawable.c1,
R.drawable.c2, R.drawable.c3,
R.drawable.c4,
R.drawable.c0, R.drawable.c1,
R.drawable.c2, R.drawable.c3,
R.drawable.c4,
R.drawable.c0, R.drawable.c1,
R.drawable.c2, R.drawable.c3,
R.drawable.c4,
R.drawable.c0, R.drawable.c1,
R.drawable.c2, R.drawable.c3,
R.drawable.c4,
R.drawable.c0, R.drawable.c1,
R.drawable.c2, R.drawable.c3,
R.drawable.c4,
R.drawable.c0, R.drawable.c1,
R.drawable.c2, R.drawable.c3,
R.drawable.c4,
R.drawable.c0, R.drawable.c1,
R.drawable.c2, R.drawable.c3,
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//gridview.getId();
imageView = (ImageView) v;
Random r=new Random();
int i=r.nextInt(16);
Log.e("i",""+i);
imageView.setImageResource(mThumbIds[i]);
ImageAdapter im = (ImageAdapter)parent.getAdapter();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// private GridItem[] items;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(40,40 ));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(3, 3, 3, 3);
} else {
imageView = (ImageView) convertView;
}
Random r=new Random();
int i=r.nextInt(5);
imageView.setImageResource(mThumbIds[i]);
return imageView;
}
}
}