我正在尝试制作一个简单的“打地鼠”风格的游戏。我陷入了第一个障碍:
我想(随机)选择布局上的按钮,然后更改其颜色。
我的 xml 布局上有三个按钮:
<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>
并且,在按下另一个(开始)按钮时,我在 java 类中执行以下操作:
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);
}
这会随机生成一个 0 到 2 之间的值,然后我加 1 并将其连接到一个字符串 (randomButtonId),以创建一个字符串,该字符串是三个按钮之一的随机选择的 Id。
显然,倒数第二行不正确,但是我如何选择实际的布局元素,因为我现在想更改它的颜色(最后一行)?
非常收到任何建议!
最佳答案
您可以使用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);
}
对于颜色,在 values
文件夹中名为 colors.xml
的文件中定义您自己的颜色,并加载它以使用 setBackgroundResource
或您可以使用activeMole.setBackgroundColor(Color.RED);
。
关于java - 选择 Android xml 布局元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21364904/