Search code examples
javaandroidandroid-studiocountdowntimer

Set Visibility after countdown ends


Despite thorough search of other user's questions, I don't seem to understand how to do a countdown timer. All I wanna do is setting visibility to GONE after 30 seconds without touching the screen. So far I've done this:

public class StatusFragment extends Fragment {
    CountDownTimer countDownTimer;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        countDownTimer = new CountDownTimer(30000, 1000) {

            public void onTick(long millisUntilFinished) {
                          //SET VISIBILITY TO VISIBLE
            }

            public void onFinish() {
                             //SET VISIBILITY TO GONE
            }
        }.start();


        cpHover.setOnClickListener(new OnClickListener() {

            //Should I countDownTimer.start()? It says there's an error
            @Override
            public void onClick(View view) {
                if(textBox.getVisibility()==View.GONE){
                    donutProgress.setVisibility(View.VISIBLE);
                    textBox.setVisibility(View.VISIBLE);
                    image.setVisibility(View.VISIBLE);


                }
                else if(textBox.getVisibility()==View.VISIBLE){
                    donutProgress.setVisibility(View.GONE);
                    textBox.setVisibility(View.GONE);
                    image.setVisibility(View.GONE);
                }
            }
        });

The process should be quite easy. Setting in onCreate() a 30-second countdown that starts every time the user clicks cpHover. When they click it again, it should restart the countdown. There are two ways of hiding the UI: clicking on the screen when it's visible or not clicking at all in 30+ seconds.

Thanks in advance.


Solution

  • add this inside your onCreate()

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
                    //set visibility as gone here
                    if(textBox.getVisibility()==View.VISIBLE){
                    donutProgress.setVisibility(View.GONE);
                    textBox.setVisibility(View.GONE);
                    image.setVisibility(View.GONE);
                }
      }
    }, 30000);