Reputation: 149
I am trying to make a simple "whack a mole" style game. I am stuck on the first hurdle:
I want to (randomly) select, and then change the color of, a button on my layout.
I have three buttons on my xml layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="3" >
<Button
android:id="@+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1" />
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2" />
<Button
android:id="@+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3" />
</LinearLayout>
And, on another (start) button being pressed, I do the following in my java class:
protected void pickRandomButton() {
// TODO Auto-generated method stub
randomButtonId = "";
Random randomGenerator = new Random(); // construct a new random number generator
int randomNumber = randomGenerator.nextInt(3);
randomButtonId = "button" + (randomNumber +1);
Log.d(TAG, randomButtonId, null);
Button activeMole = (Button) findViewById(R.id.+"randomButtonId");
activeMole.setBackgroundResource(color.red);
}
This randomly generates a value between 0 and 2, then I increment by 1 and concatenate it to a string (randomButtonId) in order to create a string which is a randomly selected Id of one of the three buttons.
Obviously, the 2nd to last line is not correct, but how do I then select the actual layout element, as I now want to change it's color (the last line)?
Any advice greatly received!
Upvotes: 0
Views: 681
Reputation: 162
Make an array of the ids.
int [] ids = {R.id.button1, R.id.button2,R.id.button3};
When you reference it in the second to last line, just use ids[randomnumber];
Also, don't add one. Keep the random between 0 and 2.
Upvotes: 0
Reputation: 93902
You can use getIdentifier
:
protected void pickRandomButton() {
// TODO Auto-generated method stub
randomButtonId = "";
Random randomGenerator = new Random(); // construct a new random number generator
int randomNumber = randomGenerator.nextInt(3);
randomButtonId = "button" + (randomNumber +1);
Log.d(TAG, randomButtonId, null);
int buttonId = getResources().getIdentifier(randomButtonId, "id", getPackageName());
Button activeMole = (Button) findViewById(buttonId);
activeMole.setBackgroundResource(color.red);
}
For the color, define your own color in a file named colors.xml
in the values
folder and load it to use setBackgroundResource
or you can use activeMole.setBackgroundColor(Color.RED);
.
Upvotes: 2