Android以编程方式声明按钮?

时间:2012-03-14 05:57:04

标签: android

在我的音板应用程序中,我有80个按钮,它们具有单击侦听器和长按单击侦听器。

我的按钮在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增加1。

3 个答案:

答案 0 :(得分: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布局。

对于同样的问题,这里有一个更明确的例子=&gt; Android – findViewById() in a loop

答案 1 :(得分:0)

是的。在for循环中,首先声明一个Button,并将其构造函数传递给上下文。然后设置每个按钮的布局参数。将每个按钮添加到父视图(在父视图上使用addView方法)。最后,使用活动的setContentView方法并将父项作为参数传递。

答案 2 :(得分: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
    }