Button click event to change image - java

Is there any method available for suppose if I click the button than the image should be change. Number of times I click the button the image should be change.

I suppose you want to change the image of an ImageView
For changing the image of an ImageView, inside the onClick() of the Button use:
myImageView.setBackgroundResource(R.drawable.my_image_name);
Here, myImageView is the object bound an ImageView, and
R.drawable.my_image_name is the location of the image file present in your Drawable folder.
For more details refer to this thread
Update
I have use a random number and switch case. When I click the button the number will be generated and pass to switch case and based on that the image should appear in the image view.
In that case, let's assume you have 3 images in your drawable folder. You can use a HashMap where the key is the index and the value is the image-path
HashMap<Integer, Integer> imageMap=new HashMap<Integer, Integer>();
imageMap.put(1,R.drawable.my_image4);
imageMap.put(2,R.drawable.my_image3);
imageMap.put(3,R.drawable.my_image2);
Now, generate Random number in range 1-3
int min = 1;
int max = 3;
int randomNumber = new Random().nextInt((max - min) + 1) + min;
Finally, set the image at the randomly generated position.
int randomImageId = imageMap.get(randomNumber);
myImageView.setBackgroundResource(randomImageId);
Hope this helps

Related

How to get correct ImageviewId after rotation of layout

I have a layout with 2*2/3*3/4*4... ImageView. and some of them randomly colored like this:
For ranodomly colored one of Imageview, I have Use this code:
Random random = new Random();
id = array_image1.get(random.nextInt(array_image1.size()));
ObjectAnimator animator = ObjectAnimator.ofInt(findViewById(id), "backgroundResource", R.drawable.original_img, R.drawable.org_state).setDuration(1500);
animator.setStartDelay(1500);
animator.setEvaluator(new ArgbEvaluator());
animator.start();
And I'm handling some click event on colored ImageView like this:
for (int i = 0; i < array_image11.size(); ++i) {
final int btn = array_image11.get(i);
findViewById(btn).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if ((findViewById(id)).equals(findViewById(btn)))
//Inform the user the button has been clicked
{
//forward
findViewById(id).setBackgroundResource(R.drawable.original_img);
}else {
//backward
Toast.makeText(StaticSpatial.this, "wrong", Toast.LENGTH_SHORT).show();
}
});
}
There is no problem till above.
But When I'm adding a random rotate animation code like this:
int n;
int[] a=new int[]{1,2};
final Random rnd = new Random();
n=a[rnd.nextInt(a.length)];
if(n==1)
{
ObjectAnimator rotateAnimator = ObjectAnimator.ofFloat(l4, View.ROTATION, 0, 90);
rotateAnimator.setDuration(2000); // miliseconds
rotateAnimator.start();n);
}
else
{
ObjectAnimator rotateAnimator = ObjectAnimator.ofFloat(l4, View.ROTATION, 0, 90);
rotateAnimator.setDuration(2000); // miliseconds
rotateAnimator.start();
}
After rotation image look like this(i.e. colored Imageview chage it's position):
After adding this rotate animation code my clickEvent not get correct ImageView id.
i.e. when imageview change it's position,their id should be go with that positon. but imageview id ramains at same postion.
So How to get required ImageviewId after rotation
Update:
After using azizbekian's answer(now using animator instead of animation) I found correct image-view id , but only first time.
i.e. first time when Activity starts it works good but when I'm going to a new view(say 3*3) and return back again to this view(2*2),it returns wrong image-view id till Activity restarts again.see my updated code for ref.
Explanation of working and issue:
I have already said that there are many matix of Imageview such as 2*2/3*3/4*4..... So when we start Application first load 2*2 matrix of imageview and when we click the odd colored imageview it goes to 3*3 matrix but when we click other than odd colored imageviewthen it goes to next level say 3*3.So when app start first time when I click on odd colored imageview it goes to 3*3 matrix but when return again on 2*2 after clicking other than odd colored imageview.and then again when we click on colored imageview it not get correct image id. and if any other query plz ask?
How to resolve this issue ?
When ImageView changes it's position, their id should go with that position. But ImageView id remains at same position.
That's because you are using Animation, which in fact doesn't change your View's position. What is does it makes an illusion of animation, so it only changes that view's matrix, but doesn't perform layout changes to the view.
Use Animator API instead of Animation.
Update
Given this animation xml:
<set xmlns:android="schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="0"
android:toDegrees="90"
android:pivotX="50%"
android:pivotY="50%"
android:duration="2000" />
</set>
This can be substituted with following:
ObjectAnimator rotateAnimator = ObjectAnimator.ofFloat(yourView, View.ROTATION, 0, 90);
rotateAnimator.setDuration(2000);
rotateAnimator.start();
Update:
Just set rotation zero at every load of view (or layout) like this:
mylayoutname.setRotation(0);
Because after rotation it doesn't go to zero degree automatically until activity stops.
Maybe instead of using rotation you can store the Ids of the ImageViews in a List or Array and the Id of the currently colored ImageView in a separated variable, and when you have to rotate instead you can simply select one random ImageView from the List/Array (excluding the currently colored one), remove the color from the previous one and color the new one.
By the way, when you have 3x3, 5x5, 7x7 etc. layouts is the middle ImageView never colored? 'Cause in those cases a rotation wouldn't change anything (visually, at least). I mean, a rotation works for choosing a random square in a layout of 2x2 squares, but not in any other case. Do you need to choose the squares randomly or do they need to always be chosen by a rotation? (I hope what I mean is clear...)

Android: How do I compare ImageSpan drawable to XML resource drawable?

I have a question which I cannot find an answer for too long and I would appreciate if you can help.
I have a TextEdit which I add icons (Emojis) into it between the text.
The Icons are stored in an ImageSpan[] array named imagesInTxt.
Then I loop through the ImageSpan[] and I am trying to compare its drawable or whatever constant value that it can offer to the resource from the XML, Eg: R.Drawable.Smiley that was used as icons in the first place.
The problem is that the unique identifier that returns from getResources().getDrawable(R.Drawable.smiley) does not match the identifier than I get from imagesInTxt[x].getDrawable(), although we are talking about the same icon exactly.
I don't want and don't see a way to use .SetTag() and .GetTag() because I am dealing with ImageSpan[] from within the EditText and not the button itself, so this solution is not helping me.
I don't want to compare the ImageSpan[] directly to the ImageView button. I need to compare it to the original resource that I used (Eg: R.Drawable.xxxx) in any way possible.
How can I achieve that ?
If it is impossible, what can you suggest as an alternative solution ?
ImageSpan[] imagesInTxt = txt.getSpans(0, txt.length(), ImageSpan.class);
for (int x = 0; x < itemSpans.length; x++) { // Go through the ICONS
Drawable myIcon = getResources().getDrawable(R.Drawable.smiley);
if(imagesInTxt[x].getDrawable().equals(myIcon)) {
Icon = ";-)";
}
myIcon = getResources().getDrawable(R.drawable.sad);
if(imagesInTxt[x].getDrawable().equals(myIcon)) {
Icon = ";-(";
}
}

Is it possible to retrieve the drawable name that's occupying an imageView that's using a random array

I have a educational kids game where the object is to match the image with the correct answer, 4 buttons provided for potential answers. The first part was to randomly fill the imageView with drawables that never repeat up to end of game. This part I have figured out and works. The part I'm having trouble with is dealing with the idea on how to compare what random image is in the imageView at that moment to
1. Make sure one of the four options is a correct answer and
2. To compare whatever is clicked to what is in the imageView at that time.
I tried imgView.getId(); , but it didn't work.
Array
private ArrayList<Integer> res1 = new ArrayList<Integer>();
int arrPos = 0;
Method that randomizes
private void randomImage1() {
Collections.shuffle(res1);
imgView.setImageResource(res1.get(arrPos));
arrPos = arrPos + 1;
}
onclick
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(counter <= 2){
imgView.setImageResource(res1.get(arrPos));
//randomImage1();
counter = counter + 1;
arrPos = arrPos+1;
System.out.println(arrPos);
Toast.makeText(getApplicationContext(), Integer.toString(counter) ,
Toast.LENGTH_SHORT).show();
}else if(counter == 3){
Toast.makeText(getApplicationContext(), Integer.toString(counter) + "Game Over",
Toast.LENGTH_SHORT).show();
}
}
});
My idea is to assign an id for each image + correct answer and maintain a list of available ids (with corresponding images and correct answers). So for your questions:
Make sure one of the four options is a correct answer
Get a random id, get the corresponding image to display and corresponding correct answer to be one of the 4 options. Take the id out from the list, get 3 other options from the rest of the id and their corresponding answers.
To compare whatever is clicked to what is in the imageView at that time.
When you display ImageView and options you can use android:tag to keep the ids of the correct answers and incorrect answers.
Then in your code, use getTag() on the view to get the ids of the image and the chosen answer for comparison.
Hope it helps.
Set an id for each image and get the id of image on click. Maintain the HashMap for comparison between the image selected and its answers.

How to change a background image of a button in Android without knowing the image name earlier?

I have some image files in drawable folder. The name of the images are like button1, button2, button3......There is also a count variable which increases by one whenever a button is clicked.What I want to do is that whenever someone click on a button image of that button should change to the image corresponding to the current value of count.
I tried
buttons[0][0].setBackground(R.drawable.button+count);
But it is not working
You can't access it directly. You'll have to get the resource using its name:
private Drawable getDrawableResourceByName(int count) {
String packageName = getPackageName();
int resId = getResources().getIdentifier("button" + String.valueOf(count), "drawable", packageName);
return getResources().getDrawable(resId);
}
Then use it as:
buttons[0][0].setBackgroundDrawable(getDrawableResourceByName(count)); //setBackground() only works with drawables from API 16

Programatically setting a random image to an ImageButton

I'm trying to have the picture used by my ImageButton to be selected randomly.
I think this code should work but there seems to be a problem when passing the resource as a String.
ImageButton getClickTime = (ImageButton) findViewById(R.id.clicker);
Random generator = new Random();
int generatedRandom = generator.nextInt(10) + 1;
String randomImage = "R.drawable.bg" + (String.valueOf(generatedRandom)) ;
Drawable replaceImage = getResources().getDrawable((int) randomImage);
getClickTime.setImageDrawable((Drawable) replaceImage);
I seem to be getting in a bit of a mess with casts of ints, Strings, drawables and CharSequences.
If I manually type in a randomly selected image resource, it works. But if I pass the String to a text-box I can see that it's written exactly the same as when I type it in manually.
Can anyone see what I'm doing wrong here?
Thanks in advance
Your problem is that you are misunderstanding how Android uses resource ids. The R file holds int ids that map to resources contained in your app. You are trying to reference a drawable resource by casting its String reference into an int. That is impossible and doesn't make sense.
What I would suggest is that you create an int[] that holds the ids of all of your drawables that you want to be randomly selected.
int[] imageIds = {
R.drawable.bg1,
R.drawable.bg2,
R.drawable.bg3,
R.drawable.bg4,
R.drawable.bg5
// etc for as many images you have
};
Then, randomly select one of those drawable ids and set that your to ImageButton.
ImageButton getClickTime = (ImageButton) findViewById(R.id.clicker);
Random generator = new Random();
int randomImageId = imageIds[generator.nextInt(imageIds.length)];
getClickTime.setImageResource(randomImageId);
If you want to get the id of a resource you should use something like this:
int id = context.getResources().getIdentifier("resource_name", "drawable", context.getPackageName());
Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), id);
You may want to use an array of all images and get it by random index:
int[] all = {
R.drawable.bg1,
R.drawable.bg2,
};

Categories