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


我只希望动态创建一个按钮

最佳答案

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

07-26 09:39