以编程方式在android中创建具有click事件的按钮

时间:2012-12-19 12:39:29

标签: android android-layout android-intent

单击一个按钮时,我正在创建一个动态按钮。即在该按钮的onClick事件下。但是每创建一个按钮就会动态创建n个按钮。

LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1);
.....

public void onClick(View arg0) {
Button topArtistbutton = new Button(SalesPanel.this, null,android.R.attr.buttonStyleSmall);
topArtistbutton.setText("Top Artist");
topArtistbutton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));topArtistbutton.setId(3);
ll.addView(topArtistbutton);
}

我只想要一个动态创建的按钮

2 个答案:

答案 0 :(得分:5)

boolean bCreate = true;
...
public void onClick(View arg0) {
    if (bCreate)
    {
         Button topArtistbutton = new Button(SalesPanel.this, null,android.R.attr.buttonStyleSmall);
         topArtistbutton.setText("Top Artist");
         topArtistbutton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));topArtistbutton.setId(3);
         ll.addView(topArtistbutton);
         bCreate = false;
    }
}

答案 1 :(得分:1)

设置标志并使用if语句检查是否已创建按钮:

boolean created = false;


public void onClick(View arg0) {
if (!created) {

    Button topArtistbutton = new Button(SalesPanel.this, null,android.R.attr.buttonStyleSmall);
    topArtistbutton.setText("Top Artist");
    topArtistbutton.setLayoutParams(new  LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    topArtistbutton.setId(3);
    ll.addView(topArtistbutton);
    created = true;
    }
}