[英]Select an Android xml layout element
我想做一個簡單的“打鼴鼠”風格的游戲。 我陷入了第一道障礙:
我想(隨機)選擇,然后更改布局上的按鈕的顏色。
我的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);
。
制作一組ID。
int [] ids = {R.id.button1,R.id.button2,R.id.button3};
當你在倒數第二行引用它時,只需使用ids [randomnumber];
另外,不要添加一個。 保持0到2之間的隨機性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.