• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 648
  • Last Modified:

How to make an invisible button in runtime

Hi Experts,

I am trying to make a button invisible when the application starts (android), but my code does not work.

      Button b3;      
    public void onCreate(Bundle icicle) {
        login = (EditText) findViewById(R.id.editText1);
        senha = (EditText) findViewById(R.id.editText2);
        b3 = (Button) findViewById(R.id.button3);
        b3.setVisibility(View.GONE);   <-- code Crash here

How to do this code works ?

1 Solution
set it to "gone" in xml resource.

besides, are you sure your b3 object is not null?
There are three visibility states for Views, controls, etc - anything subclassed from View:

VISIBLE which means just that; the item is visible, takes up space in the layout, etc

INVISIBLE which means the item takes up space in the layout, but the item itself is not visible.  (think of three buttons in a row; the middle one is INVISIBLE, so it won't be drawn, but there will be space for it between the other two buttons)

GONE which means the item is not drawn, and doesn't take up space in the layout.  if the middle button of the three-button example were GONE, then the other two buttons would be positioned as if the middle button wasn't even defined at all; they would likely be close together.

Just offhand, try checking that b3 isn't null:

    b3 = (Button) findViewById(R.id.button3);
    if (b3 != null) {
        b3.setVisibility(View.GONE);   <-- code Crash here
    } else {
        Log.i("b3 is null");

Open in new window

You can also set a breakpoint at the setVisibility line and use the debugger.

Check that whatever is named 'button3' really is a button.  (there must be something otherwise the compiler would complain that R.id.button3 doesn't exist.  it's interesting that it does crash; anything subclassed from View has setVisibility() so I wouldn't expect it to crash...)

To make it invisible right from the start, set the "android:visibility" property to GONE right in the XML file:

	android:text="Clear Message"

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now