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));
}
});
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 );
}
Whenever the user presses the button, the text of the TextView, as well as the background image of TextView, is changed. I have created an int[] array to store the id of drawable to use in TextView.setBackgroundResource(array[index]) . But on incrementing the index the background is not changed. I even tried hardcoded index for array[] but it still sets first element image.
//j and drawable array are global variable.
int j=1;
int[] drawablearray=new int[]{R.drawable.girl,R.drawable.beach,R.drawable.flower};
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(j<drawablearray.length-1){
j++;
quoteTextView.setBackgroundResource(drawablearray[j]);
quoteTextView.getBackground().setAlpha(150);
}else{
j=0;
quoteTextView.setBackgroundResource(drawablearray[j]);
quoteTextView.getBackground().setAlpha(150);
}
});
It seems everthing OK in your code.
Did you initialised nextButton properly?
Probably your click is not working.
UPDATE
I have updated your code:
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(j<drawablearray.length){
quoteTextView.setBackgroundResource(drawablearray[j]);
quoteTextView.getBackground().setAlpha(150);
j++;
}else{
quoteTextView.setBackgroundResource(R.drawable.girl);
quoteTextView.getBackground().setAlpha(150);
}
}
});
For the first 3 clicks it will show three different images then sets to default image
Your j variable must be 'global'. It means that it must a member of your Activity or Fragment but not a variable inside your method
Instead of the "if" condition I suggest you to use:
j = (j+1) % drawablearray.length;
Then the variable j must be a field of your java class (declare it outside every method)
Good morning,
How can I put multiple string ressources inside the setText to display them in order ?
I have a layout with a TextView (id: TxtDisp) and a Button (id: NextSentence) that change the text when I click on it.
NextSentence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TxtDisp.setText(R.string.sentence_2);
}
});
Where or how can I put four to six string ressources to be display in order when the button is clicked ?
Thanks in advance !
You could put the string resources in an array, and get the string from that. So add a class member to track the which sentence is next
private int nextSentenceId = 0;
then in onCreate use code like this
final int[] sentences = new int[]{R.string.sentence_1, R.string.sentence_2, R.string.sentence_3};
NextSentence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( nextSentenceId < sentences.length ) {
TxtDisp.setText(sentences[nextSentenceId]);
++nextSentenceId;
}
}
});
Make sure to catch when you are at the last sentence or you will get an array out of bounds error.
You can do it easily when you hold these strings in an array or something and have a counter that hold which string is displayed right now like so
in onCreate() method put your sentences in an ArrayList
ArrayList<Integer> strings = new ArrayList();
strings.add(R.string.sentence1);
strings.add(R.string.sentence2);
strings.add(R.string.sentence3);
then on the button click you can use the counter and track which is selected
NextSentence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TxtDisp.setText(strings.get(count++));
}
});
I hope this would help you
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.