![](/img/trans.png)
[英]Android - How do you efficiently load a large amount of text in a TextView?
[英]How do I get references to large amount of buttons in android?
在我的xml布局文件中,我有81個按鈕,如下所示:
<Button
android:id="@+id/button11"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
我知道我可以像這樣獲得參考:
playButtons[0][0] = (Button) findViewById(R.id.button11);
playButtons[0][1] = (Button) findViewById(R.id.button12);
等等,但是我如何有效地做到這一點呢?
編輯:
我想用對for循環中的XML按鈕的引用填充我的playButtons矩陣,如下所示:
for(int i = 0; i<9; i++){
for(int k = 0; k<9; k++){
playButtons[i][k] = (Button) findViewById(R.id.button11);}}
但是我不知道如何將button11更改為button12,依此類推。
我想這就是你想要的。 您必須將按鈕命名為button01,button02,button03等。
Button[][] playButtons = null;
Class id=R.id.class;
Field field = null;
for(int i = 0; i<9; i++){
for(int k = 0; k<9; k++){
try {
field = id.getField("button"+i+""+k);
playButtons[i][k] = (Button) findViewById(field.getInt(null));
} catch (NoSuchFieldException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
您是否考慮過列表視圖或網格視圖? 如果您可以使用其中任一方法,則效率會更高。 如果不是,則必須一個一個地聲明每個按鈕,但是如果使用playButtons數組,則可以使用循環將更改應用於所有按鈕,例如
for(int i = 0;i<playButtons.length;i++){
playButtons[0][i].setOnClickListener(this);
}
這將是我想到的最有效的方法...
我建議您對ID使用此語法,這樣您就不會對應用程序中的ID過多感到困惑:
android:id="@+id/your_file_name_widgetName_whatYourWidgetDo
在名為menu_settings.xml的布局文件中保存設置預設的按鈕的示例
android:id="@+id/menu_settings_button_savePreset"
當我的XML文件上有很多按鈕時,我將其注冊在數組上,如下所示:
final int[] BUTTON_ID = {
R.id.myId, R.id.anotherId, R.id.otherId,
R.id.moreId, R.id.anotherAnotherId
};
final int BUTTONS_COUNT = BUTTON_ID.lenght;
Button[] button;
@Override
public void onCreate(Bundle savedInstanceState){
...
button = new Button[BUTTONS_COUNT];
for(int i = 0; i < BUTTONS_COUNT; i++){
button[i] = (Button) findViewById(BUTTONS_ID[i]);
button[i].setOnClickListener(this); // your class should implements View.onClickListener to use "this" as argument
}
}
您告訴您布局上有81個按鈕, for
循環中的findViewById()
會在低性能循環中產生,建議您將android:onClick = "methodName"
attr添加到xml文件中的按鈕上,因此不要每個都需要使用findViewById()
。
要使用按鈕,只需將以下內容添加到Activity類中,然后執行任何您想做的事情:
public void methodName(View v){
Button b = (Button) v;
int ID = b.getId();
if(ID == R.id.buttonId){
//DO SOMETHING FOR THIS BUTTON
}
else if(ID == R.id.anotherButtonId){
//DO SOMETHING FOR THIS BUTTON
}
...
}
但是請考慮一下:您的布局確實需要這么多按鈕嗎? 想想在更好的應用程序體系結構中,單個線程的81個按鈕可能非常繁重。
希望您能理解!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.