Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

nayden picture nayden · Sep 8, 2011 · Viewed 263.7k times · Source

I want my DatePicker and the button to be invisible in the begining. And when I press my magic button I want to setVisibility(View.Visible);

The problem here is when I setVisibility(View.GONE) or setVisibility(View.INVISIBLE) nothing changes and the component is still visible.

final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
final Button btn2 = (Button) findViewById(R.id.btnDate2);

dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);

btn2.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        TextView txt2 = (TextView) findViewById(R.id.txt2);
        txt2.setText("You selected " + dp2.getDayOfMonth()
            + "/" + (dp2.getMonth() + 1) + "/" + dp2.getYear());
    }
});

Answer

con_9 picture con_9 · Sep 8, 2011

I see quite a few things wrong. For starters, you don't have your magic button defined and there is no event handler for it.

Also you shouldn't use:

dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE); 

Use only one of the two. From Android documentation:

View.GONE This view is invisible, and it doesn't take any space for layout purposes.

View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.

In your example, you are overriding the View.GONE assignment with the View.INVISIBLE one.


Try replacing:

final DatePicker dp2 = new DatePicker(this)

with:

DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);  

Similarly for other widgets:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);

        final DatePicker dp2 = new DatePicker(this);
        final Button btn2 = new Button(this);
        final Button magicButton = new Button(this);
        final TextView txt2 = new TextView(TestActivity.this);

        dp2.setVisibility(View.GONE);
        btn2.setVisibility(View.GONE);
        btn2.setText("set Date");

        btn2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                txt2.setText("You selected "
                    + dp2.getDayOfMonth() + "/" + (dp2.getMonth() + 1) 
                    + "/" + dp2.getYear());
            }
        });

        magicButton.setText("Magic Button");
        magicButton.setOnClickListener(new View.OnClickListener()    
            public void onClick(View arg0) {
                dp2.setVisibility(View.VISIBLE);
                btn2.setVisibility(View.VISIBLE);
            }
        });

    ll.addView(dp2);
    ll.addView(btn2);
    ll.addView(magicButton);
    ll.addView(txt2);

    setContentView(ll);
}