Java 选择Android xml布局元素
我想做一个简单的“打鼹鼠”式的游戏。我被困在第一个障碍上: 我想(随机)选择布局上的按钮,然后更改其颜色 我的xml布局上有三个按钮:Java 选择Android xml布局元素,java,android,xml,Java,Android,Xml,我想做一个简单的“打鼹鼠”式的游戏。我被困在第一个障碍上: 我想(随机)选择布局上的按钮,然后更改其颜色 我的xml布局上有三个按钮: <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:weightSum="3" > <Button android:id="@+id/button1"
<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>
这会随机生成一个介于0和2之间的值,然后我增加1并将其连接到一个字符串(randomButtonId),以便创建一个字符串,该字符串是三个按钮中随机选择的Id之一
很明显,从第二行到最后一行是不正确的,但是当我现在想要改变它的颜色(最后一行)时,我如何选择实际的布局元素呢
任何建议都会收到 您可以使用:
对于颜色,在
values
文件夹中名为colors.xml
的文件中定义您自己的颜色,并将其加载到setBackgroundResource
中,或者您可以使用activeMole.setBackgroundColor(color.RED)代码>创建一个ID数组
int[]id={R.id.button1,R.id.button2,R.id.button3}
当您在倒数第二行引用它时,只需使用ids[randomnumber]
另外,不要添加一个。将随机数保持在0和2之间 int[]ids=新的int[3];id={R.id.button1,R.id.button2,R.id.button3};给出错误:“数组常量只能在初始值设定项中使用”抱歉,早上在这里,我声明数组时太傻了。ZouZous方法可能比我这里的方法更易于重用。
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);
}
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);
}