Search code examples
androidbuttonvisibleinvisible

Android Button Set Button Invisible Without Click


This seems like a very simple problem, but for some reason I find myself unable to find any suitable answers that work. What I have is 2 buttons with one stacked on the other in a Frame Layout, and when Button1 is clicked, it becomes invisible and Button2 appears. What I'm trying to get to happen is after a few seconds Button2 automatically becomes invisible and Button1 is visible again. Here is the little bit of code I have. Any help would be greatly appreciated!

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


        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub 

                button1.setVisibility(Button.GONE);
                button2.setVisibility(Button.VISIBLE);

            }
        });

Solution

  • A simpler solution than many that are being proposed here would be as follows:

    button1 = (Button)findViewById(R.id.button1);
    button2 = (Button)findViewById(R.id.button2);
    
    
    button1.setOnClickListener(new View.OnClickListener() {
    
        @Override
        public void onClick(View v) {
            button1.setVisibility(Button.GONE);
            button2.setVisibility(Button.VISIBLE);
            button1.postDelayed(new Runnable() {
                @Override
                public void run() {
                    button1.setVisibility(View.VISIBLE);
                    button2.setVisibility(View.GONE);
                }
            }, 2000);
        }
    });