我是安卓新手。我已经从 res/drawable-mdpi 文件夹中手动完成了在 ImageView 和 GridView 中设置图像的操作。现在我想随机设置图像,因为刷新活动可能会更改未预定义的图片设置。以下代码是我尝试过的。请帮我。先感谢您。
TestShapeActivity.java:
公共类 TestShapeActivity 扩展 Activity {
Integer[] imageIDs={
R.drawable.cir1,
R.drawable.rect1,
R.drawable.sqr1,
R.drawable.tri1
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_shape);
ImageView imageView=
(ImageView)findViewById(R.id.Image1);
imageView.setImageResource(R.drawable.cir1);
GridView 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)
{
if(position==0){
Toast.makeText(getBaseContext(),
"Shape Matched",
Toast.LENGTH_LONG).show();
startActivity(new Intent("com.example.TestShapeActivity2"));
finish();
}
else{
Toast.makeText(getBaseContext(),
"Please Try Again",
Toast.LENGTH_LONG).show();
}
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context =c;
}
public int getCount(){
return imageIDs.length;
}
public Object getItem(int position){
return position;
}
public long getItemId(int position){
return position;
}
public View getView(int position,View convertView,
ViewGroup parent)
{
ImageView imageView;
if(convertView==null){
imageView=new ImageView(context);
imageView.setLayoutParams(new
GridView.LayoutParams(85,85));
imageView.setScaleType(
ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5,5,5,5);
} else{
imageView=(ImageView)convertView;
}
imageView.setImageResource(imageIDs[position]);
return imageView;
}
}