2012-03-14 100 views
1

在我的soundboard應用程序中,我有80個按鈕,它們具有點擊監聽器和長按聆聽器。Android以編程方式聲明按鈕?

我的按鈕,以XML作爲聲明:

<TableRow 
     android:id="@+id/tableRow1" 
     android:layout_height="wrap_content" > 

     <Button 
      android:id="@+id/sound0" 
      android:layout_width="1dip" 
      android:layout_height="fill_parent" 
      android:layout_weight=".31" 
      android:longClickable="true" 
      android:text="@string/sound0" > 
     </Button> 

     <Button 
      android:id="@+id/sound1" 
      android:layout_width="1dip" 
      android:layout_height="fill_parent" 
      android:layout_weight=".31" 
      android:longClickable="true" 
      android:text="@string/sound1" > 
     </Button> 

     <Button 
      android:id="@+id/sound2" 
      android:layout_width="1dip" 
      android:layout_height="fill_parent" 
      android:layout_weight=".31" 
      android:longClickable="true" 
      android:text="@string/sound2" > 
     </Button> 
    </TableRow> 

而且聽衆被設置爲:

Button SoundButton0 = (Button) findViewById(R.id.sound0); 
    SoundButton0.getBackground().setAlpha(150); 

    SoundButton0.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 
      String name = getString(R.string.sound0); 
      tracker.trackEvent("Clicks", "Play", name, 0); 
      playSound(R.raw.sound0); 

     } 
    }); 
    SoundButton0.setOnLongClickListener(new OnLongClickListener() { 

     public boolean onLongClick(View v) { 
      String name = getString(R.string.sound0); 
      tracker.trackEvent("Clicks", "Saved", name, 0); 
      ring(soundArray[0], name); 
      return false; 

     } 
    }); 

有沒有一種方法可以讓我的for循環做這一切的編程方式,使每個按鈕更改的唯一內容是SoundButtonx,其中每個按鈕的x增加一個。

回答

3

是的,有一個明確的解決方案:

Button[] buttons; 
for(int i=0; i<buttons.length; i++) { 
{ 
    String buttonID = "sound" + (i+1); 

    int resID = getResources().getIdentifier(buttonID, "id", getPackageName()); 
    buttons[i] = ((Button) findViewById(resID)); 
    buttons[i].setOnClickListener(this); 
} 

注:聲明與ID喜歡Sound1例子,SOUND2,sound3,sound4按鈕XML佈局....等等。

更鮮明的例子就是這裏了同樣的問題=>Android – findViewById() in a loop

+0

現在我該怎樣建立一個在點擊監聽器,將捕獲每個按鈕? – mpeerman 2012-03-14 06:11:06

+0

@mpeerman檢查示例鏈接。 – 2012-03-14 06:14:49

0

是的。在for循環中,首先聲明一個Button,並將其構造函數傳遞給一個上下文。然後你設置每個按鈕的佈局參數。將每個按鈕添加到父視圖(在父視圖中使用addView方法)。最後,使用活動的setContentView方法並將父項作爲參數傳遞。

0
yes take a look at this 

for(int x = 0;x<80;x++) 
{ 
Button btn = new Button(this); 
btn.setlayoutParams(new LayoutParams(LayoutParams.wrap_content,LayoutParams.wrap_conmtent); 
btn.setId(100 + x); 
btn.setOnClickListener(this); 
btn.setOnlongClickListener(this); 
this.addView(btn); 
} 

//this will create 80 buttons and setlisteners on them 

//in your overrides of onclick and onLongClick identiffy them as 

    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     int id = v.getId(); 
    if(id == 100 + 1) 
    { 
//your code 
    } 
相關問題