简体   繁体   中英

Android Studio, change the behavior of the back button to affect items in a RecyclerView

I have a problem regarding the back button feature together with RecyclerView, my goal is to emulate the behavior in the Contacts application, where you press and hold (long press) an item in the RecyclerView and a check box appears behind the item(s) (all of them). Then, when you press the back button, all the check boxes disappear.

Regarding the information I provided we can break the problem in two parts:

  1. First, we need to solve the long click problem, which I suspect we can use NotifyDataSetChanged() together with hiding the check boxes in the XML so that we can switch between checkbox.setVisibility(VISIBLE) and checkbox.setVisibility(GONE) .

  2. Lastly, and this is the hardest part for me, I would like that, when back button is pressed, all the check boxes disappear, instead of leaving the app.

Thank you in advance and sorry if the problem is not understandable, as this is the first time I am posting a problem and English is not my native language.

What you are describing is known as Contextual Action Mode .

You'll notice, that when you long press the item the toolbar (action bar) on top changes and shows the number of selected items and a set of action you can apply to the selected items.

Pressing the back button then cancels the action mode.

It is beyond Stackoverflow's scope to explain the whole action mode system, but you can simply search for it in the internet.

Here is a tutorial for beginners , for example.

I can give you a better answer if you post your code.

You'd probably want your adapter to contain a list of selected items. If the list has any elements, you show the checkboxes and check the ones that correspond to the list. If it is empty, you don't do that. You're correct about notifying data set changed. Long press on an item would add that item to this list. Then when your adapter re-laid out your items, it would show the checkboxes since that list would not be empty.

For the second issue, you'd want to override onBackPressed() in your activity. Then you can have some code like:

public void onBackPressed() {
    if (adapter.hasItemsSelected()) {
        adapter.clearSelection()
    } else {
        super.onBackPressed()
    }
}

You'll need to write these adapter methods. hasItemsSelected should check to see if there are elements in the selected items list and clearSelection should clear the list and notify data set changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM