Totti
Totti

Reputation: 675

Android remove button dynamically

I have a button and when I press it, i want to remove it (not make it invisible). I read that I can do that using layout.removeView(mybutton) but what is the layout ? and how can I get it in my activity

Button showQuestion;
private void initialize() {
    showQuestion = (Button) findViewById(R.id.bAnswerQuestionShowQuestion);
}
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.bAnswerQuestionShowQuestion:
                showQuestion.setVisibility(View.INVISIBLE);
                //Here i want to delete the button
                question.setVisibility(View.VISIBLE);
                theAnswer.setVisibility(View.VISIBLE);
                answerQuestion.setVisibility(View.VISIBLE);
                showChoices.setVisibility(View.VISIBLE);
                showHint.setVisibility(View.VISIBLE);
            break;
    }
}

Upvotes: 11

Views: 31266

Answers (4)

Dheeresh Singh
Dheeresh Singh

Reputation: 15701

see link

ViewGroup layout = (ViewGroup) button.getParent();
if(null!=layout) //for safety only  as you are doing onClick
  layout.removeView(button);

Upvotes: 19

Paresh Mayani
Paresh Mayani

Reputation: 128428

i have a button and when i press it , i want to remove it (not make it invisible)

=> You did as below:

 showQuestion.setVisibility(View.INVISIBLE);

Try with:

 showQuestion.setVisibility(View.GONE);

FYI, INVISIBLE just hide the view but physically present there and GONE hide as well remove the presence physically as well.

Upvotes: 15

Yogesh Somani
Yogesh Somani

Reputation: 2624

You can use

      button.setVisibility(View.GONE);

Upvotes: 4

Raghav Sood
Raghav Sood

Reputation: 82543

Layout is the parent Layout of your Button, usually a RelativeLayout or LinearLayout.

You can get it as follows:

ViewParent layout = button.getParent();

Upvotes: 1

Related Questions