I have created in my layout two ImageViews, let's call them imageviewTop and imageviewBottom.
I saved two images into the drawable (green_image.png and red_image.png).
I also added a button and want I would like to do is, when the button is clicked, one of the ImageViews will get selected randomly and from the green_image it will change to the red_image.
I already tried with creating a switch/case statement and generating a random number, like 1 or 2.
Based on this number the case statement would update either the top or bottom image.
This is working fine for 2 ImageViews, but in case I would have 100, I would need to create 100 cases in code.
I am searching for a more dynamic option.
I know how to update the image for the ImageView, I am struggling with the part, on how to select one ImageView randomly, if it is possible.
Here is the code:
public class MainActivity extends Activity {
ImageView imagevieTop, imageviewBottom;
Button randomButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagevieTop = (ImageView) findViewById(R.id.imageViewTop);
imageviewBottom = (ImageView) findViewById(R.id.imageViewBottom);
randomButton = (Button) findViewById(R.id.buttonRandom);
randomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// randomly select one of the two imageviews
// for example: randomly selected imageviewTop
// set imageresource red_image to imageviewTop
//at next start up it would select either top or bottom, 50%-50% and then assign the image to it
}
});
}
}
You could just use one ImageView, and randomize the picture you draw.
Alternatively, you could adjust this to use an array of ImageViews. Your choice.
The line you want, though, is int index = random.nextInt(imgs.length); to get a random index from the list.
public class MainActivity extends Activity {
int[] imgs = new int[] { R.drawable.green_image, R.drawable.red_image };
Button randomButton;
private final Random random = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imgView = (ImageView) findViewById(R.id.imageView);
randomButton = (Button) findViewById(R.id.buttonRandom);
randomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int index = random.nextInt(imgs.length);
// randomly select one of the two drawables
int resId = imgs[index];
// set imageresource imgView
Drawable d = getResources().getDrawable(resId);
imgView.setImageDrawable(d);
}
});
}
}
To handle the "100 ImageViews" problem, I'd recommend not copying 100 lines of code, and instead looping over reasonable ID values.
List<ImageView> imgViews = new ArrayList<ImageView>();
for (int i = 0; i < 100; i++) {
int resId = getResources().getIdentifier("imgView" + i, "id", getPackageName());
ImageView nextImg = (ImageView) findViewById(resId);
imgViews.add(nextImg);
}
In case you want to do a dynamic selection of "n" ImageView elements, then you'll need to store them in a data structure (e.g. an array, a list, etc.). For example this code will select a random ImageView from a list:
public ImageView getRandomImageView(final List<ImageView> imageViewList) {
final Random random = new Random();
//The "nextInt" method works in the half-open range [0, n), so it'll never be equal to the list size.
final int randomElement = random.nextInt(imageViewList.size());
return imageViewList.get(randomElement);
}
In your case, with two ImageView's ("imagevieTop" and "imageviewBottom") declared in fixed variables then you would need to pass them to a list or something similar in order to select one of them dynamically.
Related
I have an Integer array containing the id of finite number of images. I have an ImageButton in which I am embedding an image randomly from the above array once the ImageButton is clicked. Since the images are embedded randomly, I want to know the name of the image which is currently applied to the ImageButton every time the ImageButton is clicked.
minSDK=21 and Device API Level=29
Here is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game);
Integer[] imageIds={R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.four,R.drawable.five,R.drawable.six};
final ImageButton btn= findViewById(R.id.dice);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random gen = new Random();
int randomImg = imageIds[gen.nextInt(imageIds.length)];
btn.setImageResource(randomImg);
}
});
}
you can get the name of the resource from the resource id in this way:
String name = context.getResources().getResourceEntryName(randomImg);
I am creating a ticTacToe app, and when I click on some ImageView, I set resource of that ImageView to a specific resource(X image). Now, the problem is I want to set "O" image to some other random ImageView,
public void imageViewClicked(View view) {
ImageView counter = (ImageView) view;
counter.setImageResource(R.drawable.x);
}
Keep IDs of all avaliable ImageViews in single collection in your activity:
private List<Integer> images = new ArrayList<>();
onCreate() {
images.add(R.id.image1);
images.add(R.id.image2);
//..
}
When user clicks on some ImageView, remove it from the mentioned collection, then select random view from the rest and set resource:
onClick(View view) {
images.remove(view.getId());
int rnd = new Random().nextInt(images.size() - 1);
int id = images.get(rnd);
findViewById(id).setImageResource(R.drawable.o);
images.remove(rnd);
}
Hope it helps.
You can storage your drawable resource in a variable and manage it by turn (after each play).
First turn mydrawableResource = R.drawable.x.
Second turn mydrawableResource = R.drawable.o.
Then you set:
public void imageViewClicked(View view) {
ImageView counter = (ImageView) view;
counter.setImageResource(mydrawableResource );
}
I want to make a simple app (in Android studio) that can change the image with one button and every button press a different images goes on top of it at random. I only know how to change one photo with only one button with this code
thatImage.setImageResource(R.drawable.myimage);
But I don't know how to have multiple images ready to replace it when the user presses the button and a random. So if anyone can help me out with this I would appreciate it and thank you for the support :)
You create an array of images, and then use random number to get one of them:
int[] myImageList = new int[]{R.drawable.image1, R.drawable.image2...};
Random random = new Random();
Integer rand = random.nextInt(myImageList.length - 1) + 0;
thatImage.setImageResource(myImageList[rand]);
Strings.xml
<array name="myImages">
<item>#drawable/a</item>
<item>#drawable/b</item>
<item>#drawable/c</item>
<item>#drawable/d</item>
<item>#drawable/e</item>
</array>
for the main activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button)findViewById(R.id.btn);
final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.myImages);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Random random = new Random();
int randomInt = random.nextInt(myImages.length());
int drawableID = myImages.getResourceId(randomInt, -1);
background.setBackgroundResource(drawableID);
}
});
}
I created an ImageView and in my activity every few seconds i change the picture to a different one. I also have a button than when press, is supposed to get me the resource id of the picture currently being displayed, the problem is that everytime i do:
ImageView view = (ImageView) findViewById(R.id.imageView1);
It always gives me the resourceId defined in the xml, not the one i changed dynamically, how can i achieve this? here's the code in my activity class:
public void startImages(View v) {
...
delayedImage(0);
}
private void delayedImage(final int index) {
//stop at the 5th picture
if (index > 5) return;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
String drawableId = "picture" +index;
int resourceId = getResources().getIdentifier(drawableId, "drawable", getPackageName());
ImageView view = (ImageView) findViewById(R.id.imageView1);
view.setImageResource(resourceId);
delayedImage(index+1);
}
}, 500);
}
So every 5 second a new image is set, when i click on the button Share I want to retrieve whatever resourceId is currently in the ImageView set in the method above.
//send image to send text
public void shareImage(View v){
ImageView view = (ImageView) findViewById(R.id.imageView1);
??????
}
I checked the ImageView object while debugging and I saw someone get the int by doing this:
Field f = ImageView.class.getDeclaredField("mResource");
f.setAccessible(true);
Object out = f.get(view);
But i'm unable to get the actual R drawable name from this which I need when i'm trying to retrieve it from
String path = "android.resource://your.package.name/" +getPackageName() +"/" +???;
.. can anyone please help?
In my application, I have button and ImageView.
Here when i press button i want to change ImageView. I have 5 images in my drawable folder. On press button ImageView changes images one by one based on button click. I want it's solution.
Grateful to anyone that can help.
Maintain an array of image ids and inside onClick, set images using id from the array, then increment index.
Eg:-
ArrayList<Integer> ids=new ArrayList<Integer>();
ids.add(R.drawable.image1);
ids.add(R.drawable.image2);
ids.add(R.drawable.image3);
ids.add(R.drawable.image4);
ids.add(R.drawable.image5);
Int index=0
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(index<ids.size()){
imageview.setImageResource(ids.get(index));
index++;
}
else index=0;
}
});
As #Nizam said just maintain an array of id and load dinamically the image in the onClick(). Instead of the Random use a field variable and increment it. Be careful to the array length!
final int[] ids = new int[] { R.drawable.img1, R.drawable.img2 };
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int randomId = new Random().nextInt(ids.length);
ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setImageDrawable(getResources().getDrawable(randomId));
}
});