使用另一个片段中的数据更新片段中RecyclerView中的数据

时间:2019-03-23 14:42:15

标签: android android-fragments kotlin android-recyclerview interface

我有一个AllMoviesActivity和两个片段。第一个是MovieFragment,另一个是UpdateMovieFragment

我正在RecyclerView中的MovieFragment中放映所有电影。 Movie模型类的结构为:

class Movie() : Parcelable {
    var movieID: String? = ""
    var movieName: String? = ""
    var movieImage: Uri? = null
    ...
}

每当我单击ImageViewMovie项的RecyclerView时,它就会转到UpdateMovieFragment,在那里我选择电影的图像并输入电影的名称。电影。我正在通过将Movie Item设置为Fragment's Argument从MovieFragment类从UpdateMovieFragment过渡到MovieAdapter

val fragment = UpdateMovieFragment()
            val bundle = Bundle()
            bundle.putParcelable("movie", allMovies[p1])
            fragment.arguments = bundle
            val transaction = (activity as FragmentActivity).supportFragmentManager.beginTransaction()
            transaction.addToBackStack(null)
            transaction.replace(R.id.frame_layout, fragment).commit()

现在,我将每部电影的当前时间设置为MovieID,以使其保持唯一,以便稍后在RecyclerView上更新该特定电影项目。

现在,我在活动中使用菜单按钮执行两个片段的提交操作。每当单击“提交”按钮时,我都会检查显示的片段。如果它是UpdateMovieFragment,那么我的目标是将更新后的电影返回给MovieFragment。

override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_save -> {
                val fragment = supportFragmentManager.findFragmentById(R.id.list_fragment_container)
                when (fragment) {
                    is UpdateMovieFragment -> {
                        supportFragmentManager.popBackStack()

                        val fragmentNew = supportFragmentManager.findFragmentByTag("LIST")
                        if (fragmentNew is MovieFragment) {
                            fragmentNew.refreshMovies(fragment.movie)
                        } else {
                            CommonMethods().showToast(applicationContext, "UpdateMovieFragment")
                        }
                    }

                    is MovieFragment -> {
                        CommonMethods().showToast(applicationContext, "Do nothing for now")
                    }
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

在这里,我没有收到MovieFragment中更新的电影。对于refreshMovies方法,我正在这样做:

fun refreshMovies(movie: Movie) {
        for (i in 0 until movieItems.size) {
            val secondItem = movieItems[i]

            if (movie.movieID == secondItem.movieID) {
                rankItems[i] = rankItem
                break
            }
        }

        itemAdapter.notifyDataSetChanged()
    }

解决此问题的最佳方法是什么?

0 个答案:

没有答案