1

I am creating a dynamically buttons when one button is clicked. i.e. under onClick event of that button. But it is creating n number of button dynamically for every click one button is created.

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

i want only one button created dynamically

2 Answers 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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Set the flag and use if statement to check whether button is already created or not:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.