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

前端 未结 11 2148
[愿得一人]
[愿得一人] 2020-12-02 12:51

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

11条回答
  •  我在风中等你
    2020-12-02 13:40

    View.GONE makes the view invisible without the view taking up space in the layout. View.INVISIBLE makes the view just invisible still taking up space.

    You are first using GONE and then INVISIBLE on the same view.Since, the code is executed sequentially, first the view becomes GONE then it is overridden by the INVISIBLE type still taking up space.

    You should add button listener on the button and inside the onClick() method make the views visible. This should be the logic according to me in your onCreate() method.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
    
        final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
        final Button btn2 = (Button) findViewById(R.id.btnDate2);
        final Button btn3 = (Button) findViewById(R.id.btnVisibility);
    
        dp2.setVisibility(View.INVISIBLE);
        btn2.setVisibility(View.INVISIBLE);
    
        bt3.setOnClickListener(new View.OnCLickListener(){ 
        @Override
        public void onClick(View view)
        {
            dp2.setVisibility(View.VISIBLE);
            bt2.setVisibility(View.VISIBLE);
        }
      });
    }
    

    I think this should work easily. Hope this helps.

提交回复
热议问题