Suppose that I have two ImageButtons, a HashMap
, and pictures in drawable(resources) that are placed in this HashMap
as a value.
I need to randomly choose a value from the HashMap
by key using Randomizer and then assign this value (that is a picture) to the ImageButton
as it's background.
For example, if the first button is clicked, the second button's background will be randomly changed.
So this is what I already have:
public class MainActivity extends Activity {
final Resources res = getResources();
final Random random = new Random();
final ImageButton imgButt1 = (ImageButton) findViewById(R.id.imageButton1);
final ImageButton imgButt2 = (ImageButton) findViewById(R.id.imageButton2);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Drawable coub1 = res.getDrawable(R.drawable.coub1);
Drawable coub2 = res.getDrawable(R.drawable.coub2);
Drawable coub3 = res.getDrawable(R.drawable.coub3);
Drawable coub4 = res.getDrawable(R.drawable.coub4);
Drawable coub5 = res.getDrawable(R.drawable.coub5);
Drawable coub6 = res.getDrawable(R.drawable.coub6);
Drawable coub7 = res.getDrawable(R.drawable.coub7);
Drawable coub8 = res.getDrawable(R.drawable.coub8);
Drawable coub9 = res.getDrawable(R.drawable.coub9);
Drawable coub10 = res.getDrawable(R.drawable.coub10);
final Map<Integer,Object> someHashMap = new HashMap<Integer,Object>();
someHashMap.put(1, coub1);
someHashMap.put(2, coub2);
someHashMap.put(3, coub3);
someHashMap.put(4, coub4);
someHashMap.put(5, coub5);
someHashMap.put(6, coub6);
someHashMap.put(7, coub7);
someHashMap.put(8, coub8);
someHashMap.put(9, coub9);
someHashMap.put(10, coub1);
imgButt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Object[] values = someHashMap.values().toArray();
Object randomValue = values[random.nextInt(values.length)];
int drawableID = values.;
imgButt2.setBackgroundResource(drawableID);
}
});
imgButt2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Object[] values = someHashMap.values().toArray();
Object randomValue = values[random.nextInt(values.length)];
int drawableID = myImages.getResourceId(randomInt, -1);
imgButt1.setBackgroundResource(drawableID);
}
});
}
}