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

Ami*_*nne 1 android android-intent android-layout

单击一个按钮时,我正在创建一个动态按钮.即在该按钮的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);
}
Run Code Online (Sandbox Code Playgroud)

我只想动态创建一个按钮

Mys*_*icϡ 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;
    }
}
Run Code Online (Sandbox Code Playgroud)