我是Android新手。我已经完成了手动从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;
}
}
答案 0 :(得分:0)
你可以试试这段代码。
Random generator = new Random();
yourIntResources = generator.nextInt(yourIntResources );
view.setImageResource(yourIntResources);
答案 1 :(得分:0)
Random r; // initialize this
private int getRandomImage()
{
r = new Random();
int select = r.nextInt(imageIDs.length);
return imageIDs[select];
}
并将其设置为图像视图,如下所示
ImageView imageView=
(ImageView)findViewById(R.id.Image1);
imageView.setImageResource(getRandomImage());