1

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

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

4

2 回答 2

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;
    }
}
于 2012-12-19T12:43:17.273 回答
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;
    }
}
于 2012-12-19T12:47:39.480 回答