Home > Software design >  Android - On back press
Android - On back press

Time:11-23

I am writing a code for onBackPressed() method. Actually, I want that if the user click on back press it check that If the RecyclerView is visible then it should just close the RecyclerView or if it is invisible it should go to another activity.

How I can do it ? Thanks

CodePudding user response:

Assume you have done something like recyclerView = findViewById(R.id.something) already.

@Override
public void onBackPressed() {
    if (recyclerView.getVisibility() == View.VISIBLE) {
        recyclerView.setVisibility(View.INVISIBLE);      
    } else {
        super.onBackPressed();
    }
}

As suggested by @bruno above, actually you have the answer in mind already. All you have to do is implement it and see if it works.

CodePudding user response:

Simple you can check the visibilty of the recyclerView like

if ( recyclerView.getVisibility() == View.VISIBLE )

and can can decision what you want to do.

For Example: You have to @Override onBackPressed() function to manage your logic like this:

@Override
public void onBackPressed() {
    if (recyclerView.getVisibility() == View.VISIBLE) {
         //do it here when recyclerview in visible
    } else {
        //go to any activity or 
       //simply supper method will take you on previous activity
        super.onBackPressed();
    }
}
  • Related