如果我已經在xml中創建了一個按鈕,並且我想多次使用此按鈕,但是給它們指定了唯一的ID,那麼我該怎麼做?我不知道我會有多少個按鈕,所以我無法在我的xml文件中創建多個按鈕。我希望能夠在運行程序時更改按鈕ID。我試圖做button.setId(),但一切都打破了,不會工作。在XMLAndroid按鈕ID
2
A
回答
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"
/>
相關問題
- 1. Android按鈕整數ID
- 2. Android:分配按鈕時獲取一個空值按鈕ID
- 3. Android:找到充氣按鈕的ID
- 4. Android ActionBar錯誤的主頁按鈕ID
- 5. 找不到按鈕的ID在Android的
- 6. HTML jquery按鈕ID
- 7. 按鈕選擇ID
- 8. 獲取按鈕ID不整個按鈕
- 9. Android設置onClick爲沒有ID或未知ID的按鈕
- 10. 如何在Android中按ID查找單選按鈕?
- 11. Android多按鈕按
- 12. 一鍵訪問其他按鈕的值基於該按鈕的ID在android
- 13. Android Null按鈕
- 14. Android按鈕isPressed
- 15. Android expandableListAdapter按鈕
- 16. Android按鈕onClickListener
- 17. Android,onClick按鈕
- 18. onSaveInstanceState()Android按鈕
- 19. Android Widget按鈕
- 20. Android MediaSession按鈕
- 21. Android XML按鈕
- 22. Android Studio按鈕
- 23. Android- Listview-按鈕
- 24. Highcharts渲染器按鈕ID
- 25. Asp圖像按鈕OnClientClick(id)
- 26. 按鈕ID的內部OnPostExecute
- 27. Findviewby ID找不到按鈕
- 28. kivy按鈕ID的功能
- 29. AngularJS檢測按鈕ID
- 30. PHP獲取按鈕ID
這應該是正確的答案,如果OP不希望動態創建btn – M4tchB0X3r 2016-07-18 20:05:16