简体   繁体   中英

How can I delete item from RecyclerView adapter's ArrayList, if I need to do it from another Fragment

:)

I have screen with FrameLayout flShow to show inside it DetailsFragment and ListFragment . I add to FrameLayour flShow ListFragment with RecyclerView of val listOfItems: ArrayList<Item> When I click on any item from RecyclerView, I replace FrameLayour flShow with DetailsFragment . When I click on button btDelete (which located in fragment_details.xml ) I want to delete current opened item from listOfItems . How can I do it?

fragment_Details.xml has few TextViews with Item.info and Button btDelete to delete this item from listOfItems .

You have two fragments. in 1st fragment youu have a list & in 2nd fragment you want to delete an item from list.

You can do this scenario in two ways:

1- Add line below to app level of gradle

implementation "androidx.fragment:fragment-ktx:1.5.1"

Then after pushing delete button in second fragment you should pass ID of deleted item to first fragment by code below (I suppose that Id is 1)

setFragmentResult(
                    requestKey = "key",
                    result = bundleOf(
                        "id" to 1,
                    )
                )

now you should observe key in 1st fragment by code below

setFragmentResultListener(requestKey = "key") { _, bundle -> val id = bundle.getInt("id")}

after getting id in code above delete item from list

2- You can Share data between fragments by sharedViewModel There is a full tutorial in the link below SharedViewModel Tutorial Link

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