0

我是安卓新手。我已经从 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;
    }
}
4

2 回答 2

0

你可以试试这段代码。

   Random generator = new Random();
        yourIntResources = generator.nextInt(yourIntResources );
    view.setImageResource(yourIntResources);
于 2013-06-28T12:05:08.470 回答
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());
于 2013-06-28T13:16:10.357 回答