简体   繁体   English

单击警报生成器 Android 中的项目时更改/更新回收站查看项目

[英]Change/Update Recycler View Item On Click of Item In Alert Builder Android

I want to implement a sort/filter kind of system where:我想实现一种排序/过滤系统,其中:

  • A user clicks an AlertBuilder, he sees "sort by name" and "sort by date".用户单击 AlertBuilder,他会看到“按名称排序”和“按日期排序”。
  • On click of any of them, the recyclerview should be updated.点击其中任何一个,recyclerview 应该被更新。

What I tried:我尝试了什么:

MusicDataBase音乐数据库

Where I am getting all songs and performing a sort based on user selection.我在哪里获取所有歌曲并根据用户选择进行排序。 (I am using dataStore to save user preference) (我正在使用 dataStore 来保存用户首选项)

    fun getSongs(): List<Songs> {
    val preferenceStorageImpl = PreferenceStorageImpl(context)
    preferenceStorageImpl.sortOrder().asLiveData().observeForever(Observer {
       if (it == "name"){
            sortMusic = "${MediaStore.Audio.Media.DISPLAY_NAME} ASC"
        }
        else{
            sortMusic = "${MediaStore.Audio.Media.DATE_ADDED} DESC"
        }
    })
    //Get songs from provider
    context.contentResolver.query(
        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
        projection,
        selection,
        null,
        sortMusic //Sort in alphabetical or date order based on what was selected (Default - alphabetical).
    ).use

AllSongsAdapter AllSongsAdapter

    private val diffCallback = object : DiffUtil.ItemCallback<Songs>() {
    override fun areItemsTheSame(oldItem: Songs, newItem: Songs): Boolean {          return oldItem.mediaId == newItem.mediaId
    }
    override fun areContentsTheSame(oldItem: Songs, newItem: Songs): Boolean {
        return oldItem.hashCode() == newItem.hashCode()
    }
}
 var songs: List<Songs>
    get() = differ.currentList
    set(value) = differ.submitList(value)

  .......//onbindviewholder
 override fun onBindViewHolder(holder: AllSongsViewHolder, position: Int) 
 {
    val song = songs[position]
    with(holder) {
        with(songs[position]) {
        .......
  }}

SongFragment歌曲片段

//Observe and show all songs
 mainViewModel.mediaItems.observe(viewLifecycleOwner){ result ->
        when(result.status){
            Status.SUCCESS -> {
                result.data?.let { songs ->
                    allSongsAdapter.songs = songs
                    allSongs = songs
                }
            }
            Status.ERROR -> Unit
            Status.LOADING -> Unit
        }
    }

//AlertBuilder, On click of sort by name or date
 private fun sortByName(){
    val sortOptionName = "name"
    storageViewModel.changeSortOption(sortOptionName)
    allSongsAdapter.notifyDataSetChanged()
}

private fun sortByDateAdded(){
    val sortOptionDate = "date"
    storageViewModel.changeSortOption(sortOptionDate)
    allSongsAdapter.notifyDataSetChanged()
}

StorageViewModel存储视图模型

class StorageViewModel @ViewModelInject constructor(private val 
preferenceStorage: PreferenceStorage) : ViewModel() {
val sortOrder = preferenceStorage.sortOrder().asLiveData()
fun changeSortOption(order: String) {
    viewModelScope.launch {
        preferenceStorage.setSortOrder(order)
    }
 }
}

I have also tried to call我也试过打电话

  • allSongsAdapter.notifyDataSetChanged() from MusicDatabase when the value of the sortOption changes当 sortOption 的值更改时,来自 MusicDatabase 的allSongsAdapter.notifyDataSetChanged()

eg例如

 if (it == "name"){
 sortMusic = "${MediaStore.Audio.Media.DISPLAY_NAME} ASC"
 allSongsAdapter.notifyDataSetChanged()
  }

Didn't work.没用。

When I close the app, and open, the music list is sorted fine (According to the last sort option selected)当我关闭应用程序并打开时,音乐列表排序良好(根据最后选择的排序选项)

But it is not updated real time (The moment the user clicks sort by name or date)但它不是实时更新的(用户点击按名称或日期排序的那一刻)

You can recreate adapter every time when you want to update or in case you can use diffutil which is efficient compare to recreate whole recycler view or use invalidate() recycler view this will reinitalize it您可以在每次要更新时重新创建适配器,或者如果您可以使用diffutil有效地比较重新创建整个回收器视图或使用invalidate()回收器视图,这将重新初始化它

recreate adapter as follows in kotlin:在 kotlin 中重新创建适配器,如下所示:

private fun createAdapter() {
        val mLinearLayoutManager = GridLayoutManager(context, 2)
        mRecyclerViewMediaList.layoutManager = mLinearLayoutManager
        itemListSaved = getListFiles(
            File(
                Environment.getExternalStorageDirectory()
                    .toString() + DIRECTORY_TO_SAVE_MEDIA_NOW
            )
        )!!
          mRecyclerViewMediaList.adapter = mRecyclerViewMediaAdapte  
    }

call where you called notifydatasetchanged()在您调用 notifydatasetchanged() 的地方调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android:Recycler 视图的 UI 在项目点击时不会改变? - Android: Recycler view's UI doesn't change on item click? 项目单击以进入回收站视图 - item click for recycler view Android-在回收站视图中单击项目退出活动 - Android - exit activity on item click in recycler view Android Espresso如何在Recycler View中单击Recycler View中的项目? - How Android Espresso click an item in Recycler View inside Recycler View? 更新活动中的视图以响应回收者视图项目单击 - Update View in Activity in response to recycler view item click 回收者视图的项目背景不会在点击事件中更新吗? - Recycler view's item background doesn't update on click events? 单击回收者视图中的项目后,在回收者视图中显示子项目 - Show a sub item on the recycler view after click on an item in the recycler view 导航项更改不会更新回收者视图 - Navigation item change doesn't update recycler view Android:从微调框选择的项目上的“更新回收站”视图所需的建议 - Android: Suggestion required for Update recycler view on item selected from spinner 如何在 android 嵌套回收器视图中更新内部适配器项 - How to update inner adapter item in android nested recycler view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM