通过单击事件在android中以编程方式创建按钮

通过单击事件在android中以编程方式创建按钮,android,android-layout,android-intent,Android,Android Layout,Android Intent,单击一个按钮时,我正在创建一个动态按钮。i、 e.在该按钮的onClick事件下。但它为每次点击动态创建n个按钮,并创建一个按钮 LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1); ..... public void onClick(View arg0) { Button topArtistbutton = new Button(SalesPanel.this, null,android.R.attr.butto

单击一个按钮时,我正在创建一个动态按钮。i、 e.在该按钮的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);
}

我只希望动态创建一个按钮设置标志并使用if语句检查按钮是否已创建:

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;
    }
}
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;
    }
}

设置标志并使用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;
    }
}