0

I'm a newbie on android. can you help me with this? I want to hide or show a button in a layout, but not when it is clicked. I mean, when the layout appears, the button is showed or hidden, depending on an if condition in java.

the xml is:

<Button
    android:layout_width="@dimen/icon_width1"
    android:layout_height="@dimen/icon_width1"
    android:id = "@+id/button1"

    android:background="@drawable/facebook"
    android:paddingRight="@dimen/space_1"
    android:onClick="browser1"
    android:layout_gravity="center_horizontal"
    android:layout_marginLeft="10dp" 
/>

and in my DetailActivity.java I have a function

public void browser1(View view) {
    Intent browserIntent=new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.twitter.com"));
    startActivity(browserIntent);
}

can someone help with this? Regards!

f-CJ
  • 4,235
  • 2
  • 30
  • 28
  • I'm not sure I understood, but maybe this can help: `button.setVisibility(View.INVISIBLE)` – Omar Aflak Aug 14 '16 at 14:09
  • 3
    Does this answer your question? [How to hide a button programmatically?](https://stackoverflow.com/questions/6173400/how-to-hide-a-button-programmatically) – Josh Correia Aug 14 '20 at 03:14

2 Answers2

3

@A.Omar First you have to define a button in your layout xml file like this

<Button
         android:layout_width="wrap_content"
         android:text="Test Button"
         android:id="@+id/testButtonId"
         android:layout_height="wrap_content" />

then in your activity class, in the onCreate method get your button pragmatically and set the visibility of button when the button layout appears. like this

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);

    Button testButton=(Button)findViewById(R.id.testButtonId);
            if (testButton.getVisibility()==View.VISIBLE){
                testButton.setVisibility(View.GONE);
            }else {
                  testButton.setVisibility(View.VISIBLE);
            }

}

Note make sure you don'y have two onCreate method, othervise you will get the error onCreate method is already define.

Muazzam A.
  • 647
  • 5
  • 17
1

You'll have to use the ID assigned to the button in XML, to find it in your Java code, then you can show/hide it.

The code will look like this:

Button myButton = (Button) findViewById(R.id.button1);

So your onCreate() code in an Activity would look like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);

    Button myButton = (Button) findViewById(R.id.button1);

    if(shouldShowButton()) {
        myButton.setVisibility(View.VISIBLE);
    } else {
        myButton.setVisibility(View.GONE);
    }
}
Moonbloom
  • 7,738
  • 3
  • 26
  • 38