2011-05-03 66 views
2

如果我已經在xml中創建了一個按鈕,並且我想多次使用此按鈕,但是給它們指定了唯一的ID,那麼我該怎麼做?我不知道我會有多少個按鈕,所以我無法在我的xml文件中創建多個按鈕。我希望能夠在運行程序時更改按鈕ID。我試圖做button.setId(),但一切都打破了,不會工作。在XMLAndroid按鈕ID

回答

0

給予ID喜歡

<Button android:id="@+id/close" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:text="@string/title_close" /> 
1

的問題不是很清楚,但我想你可以使用動態按鈕創建。

Button button = new Button(); 
// init it here 

layout.add(button, new LayoutParams(...)); 
0

當您不確定在某個窗口小部件的應用程序中需要的實例時,請進行動態創建。 XML主要用於靜態創建。

1

您可以創建一個獨立的button.xml文件(甚至可以將其作爲樣式),然後根據需要在代碼中填充該文件。

例如,假設您有一組代表國家/地區列表的字符串,並且您希望每個國家都有一個按鈕。這很好,因爲如果你添加或刪除任何,你只需要修改數組,而不是你的xml或for循環。

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); 
String[] countries = {"US", "Canada", "UK", "Australia"}; 
String country; 
// Don't forget to add the following layout to your xml. 
LinearLayout buttonLayout = (LinearLayout) findViewById(R.id.buttonLayout); 
buttonLayout.removeAllViews(); 
for (int i = 0; i < countries.length(); i++) { 
    country = countries.getString(i); 
    Button temp = (Button)inflater.inflate(R.layout.button); 
    // Don't forget that id is an int, not a string. 
    button.setId(id); 
    button.setText(country); 
    buttonLayout.addView(temp); 
} 

獎勵:您還可以包括在另一個XML文件這個按鈕,並在包括語句更新ID如下:

<include layout="@layout/button" 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Button 1" 
/> 
+0

這應該是正確的答案,如果OP不希望動態創建btn – M4tchB0X3r 2016-07-18 20:05:16