Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - how to make a button display on a condition?

Tags:

android

I have a button that basically looks like this:

 <Button
    android:id="@+id/admin_new_questions"        
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="See Asked Questions"
    />    

and I try to display it only in some cases like this:

if ( clause )
{
        Button admin_see_questions = (Button)findViewById(R.id.admin_new_questions);   
        admin_see_questions.setOnClickListener(new Button.OnClickListener() 
        {  
            public void onClick(View v) 
            {
           ....    
            }
        });        
}

But for some reason, the button is displayed for all cases, but the listenter is not being listened to if the clause is an error.

How can I make the button show up only when the clause is true?

Thanks!

like image 235
GeekedOut Avatar asked Dec 03 '22 04:12

GeekedOut


1 Answers

Your button is in the XML layout, so you can hide it or show it by just changing its visibility

NB: You only need do these operations once:

  1. Get a reference to your button, with findViewById()
  2. Set the OnClickListener of the button

    <Button
    android:id="@+id/admin_new_questions"        
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="See Asked Questions"
    
    android:visibility="invisible" //Initially hide the button
    
    />    
    

-

Button admin_see_questions = (Button)findViewById(R.id.admin_new_questions);   
admin_see_questions.setOnClickListener(new Button.OnClickListener() 
{  
    public void onClick(View v) 
    {
        ....       
    }
});  

if ( clause )
{
    admin_see_questions.setVisibility(View.VISIBLE); //SHOW the button
}
like image 128
Sébastien Avatar answered Dec 05 '22 18:12

Sébastien