2011-02-01 18 views
48

我正在製作一個Android應用程序,其中有一個由數百個按鈕組成的視圖,每個按鈕都有一個特定的回調。現在,我想使用循環來設置這些回調,而不必編寫數百行代碼(針對每個按鈕)。Android:使用findViewById()與字符串/在循環中

我的問題是:我怎樣才能使用findViewById靜態不必鍵入每個按鈕ID? 這裏是我想要做的:

for(int i=0; i<some_value; i++) { 
     for(int j=0; j<some_other_value; j++) { 
     String buttonID = "btn" + i + "-" + j; 
     buttons[i][j] = ((Button) findViewById(R.id.buttonID)); 
     buttons[i][j].setOnClickListener(this); 
     } 
    } 

在此先感謝!

回答

81

我應該使用getIdentifier()

for(int i=0; i<some_value; i++) { 
    for(int j=0; j<some_other_value; j++) { 
    String buttonID = "btn" + i + "-" + j; 
    int resID = getResources().getIdentifier(buttonID, "id", getPackageName()); 
    buttons[i][j] = ((Button) findViewById(resID)); 
    buttons[i][j].setOnClickListener(this); 
    } 
} 
+0

謝謝,那就是我一直在尋找的。 – user573536 2011-02-01 17:20:53

3

你可以嘗試做的是保存所有按鈕的ID,然後遍歷是一個int []:

int[] buttonIDs = new int[] {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... } 

for(int i=0; i<buttonIDs.length; i++) { 
    Button b = (Button) findViewById(buttonIDs[i]); 
    b.setOnClickListener(this); 
} 
3
+1

@ user573536請注意,在循環中使用`getResources()。getIdentifier()`會導致性能在您有大量查找時降級。 – 2011-02-01 16:47:56

+0

你說得對。我建議這種方法只在資源有順序或順序並且有很多資源(創建50個資源異味的數組)時使用。 – Cristian 2011-02-01 17:03:49

1

如果你想訪問,你可以使用標籤。

onClick

int i=Integer.parseInt(v.getTag); 

但是你不能像這樣訪問該按鈕。

只需創建按鈕編程

通過

0

創建Java代碼,而在XML中自定義按鈕如下圖所示

Button bs_text[]= new Button[some_value]; 

    for(int z=0;z<some_value;z++) 
     { 
      try 
      { 

      bs_text[z] = (Button) new Button(this); 

      } 
      catch(ArrayIndexOutOfBoundsException e) 
      { 
       Log.d("ArrayIndexOutOfBoundsException",e.toString()); 
      } 
     } 
0

如果您的頂級視圖只有那些,但噸的意見,你可以做

for (int i = 0 ; i < yourView.getChildCount(); i++) { 
    Button b = (Button) yourView.getChildAt(i); 
    b.setOnClickListener(xxxx); 
} 

如果有更多的意見目前你需要檢查如果選定的一個是你的按鈕之一。