Random image on ImageView

2019-02-21 04:22发布

I am very new to Eclipse, and have been using it only for a day so far, and also have no previous experience with Java, although I don't know much I still understand how it goes.

Could someone please help me out with a code to randomly generate a picture from my drawings folder? I got my android application blank and on full screen mode, I have added a picture in imageView1, fitCenter'ed it and it really works good, I cleaned out all the errors that occurred along the way also.

This is how my ImageView code looks so far:

<ImageView
        android:id="@+id/imageView1"
        android:contentDescription="@string/desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:scaleType="fitCenter"
        android:src="@drawable/img1" />

Now what I really need is that my application only shows a random image, and every time I run the app it shows a different image, and also that once in application, I can On Click on the image and then it shows a different random image.

I guess I have to add some strings or something, I'm really new to this and don't know much yet.

Really appreciate if you could help me out here :).

2条回答
We Are One
2楼-- · 2019-02-21 05:02

That is no "code" it's just the layout.

In your Activity you need to do the following:

1) Resolve your Imageview so that you can change the drawable.

2) Bind a click listener to it.

3a) Place all your image references in an array/list/something so that you can use them easily.

3b) Or resolve them dynamically based on name after you randomize, pic1, pic2 etc.

4) Create a random image method, randomize a number between 0 and the amount of pics.

5) Set the pic.

6) Profit

查看更多
Anthone
3楼-- · 2019-02-21 05:03

Try this

int[] photos={R.drawable.image1, R.drawable.image2,R.drawable.image3,R.drawable.image4};

ImageView image = (ImageView) findViewById(R.id.imageview1);

Random ran=new Random();
int i=ran.nextInt(photos.length);
image.setImageResource(photos[i]);
image.setOnClickListener(new View.onClickListener()
{
    public void onClick(View v)
    {
      int k=ran.nextInt(photos.length);
      image.setImageResource(photos[k]);
    }
}
);

Note: I haven't typed this in Eclipse or in any java editor, if you find any syntax error correct it by yourself.

查看更多
登录 后发表回答