【问题标题】:RecyclerView Room items not showingRecyclerView 房间项目未显示
【发布时间】:2021-06-23 20:30:41
【问题描述】:

我试图在 RecyclerView 中显示数据库中的项目,但列表未显示。我已经验证在 adapter.submitList() 中传递的列表不为空,但适配器创建方法似乎没有触发,我不知道为什么。现在这两天,非常感谢任何指针

class ScoreListAdapter : ListAdapter<Score, ScoreListAdapter.ScoreViewHolder>(ScoresComparator()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ScoreViewHolder {
        Log.i("ScoreListAdapter", "creating viewholder------->")
        return ScoreViewHolder.create(parent)
    }

    override fun onBindViewHolder(holder: ScoreViewHolder, position: Int) {
        val current = getItem(position)
        Log.i("ScoreListAdapter", "binding viewholder----------->")
        holder.bind(current.score.toString())
    }

    class ScoreViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val scoreItemView: TextView = itemView.findViewById(R.id.score_textview)

        fun bind(text: String?) {
            Log.i("ScoreListAdapter", "binding----------->")
            scoreItemView.text = text
        }

        companion object {
            //handles inflation

            fun create(parent: ViewGroup): ScoreViewHolder {
                Log.i("ScoreListAdapter", "inflating a view----------->")
                val view: View = LayoutInflater.from(parent.context)
                    .inflate(R.layout.recyclerview_item, parent, false)
                return ScoreViewHolder(view)
            }
        }
    }

    class ScoresComparator : DiffUtil.ItemCallback<Score>() {
        override fun areItemsTheSame(oldItem: Score, newItem: Score): Boolean {
            Log.i("ScoreListAdapter", "asking if items same ===  ----------->" )
            return oldItem === newItem
        }

        override fun areContentsTheSame(oldItem: Score, newItem: Score): Boolean {
            Log.i("ScoreListAdapter", "asking if items same == ----------->")
            return oldItem.score == newItem.score
        }
    }
}

class HighScoresFragment : Fragment() {

    private val viewModel:GameViewModel by activityViewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val recyclerView = activity?.findViewById<RecyclerView>(R.id.recyclerview)
        val adapter = ScoreListAdapter()
        recyclerView?.adapter = adapter
        recyclerView?.layoutManager = LinearLayoutManager(context)

        viewModel.allScores.observe(this, Observer { scores ->
            // Update the cached copy of the scores in the adapter.

            scores?.let {
                Log.i("HighScoresFragment", "adapter submitting list --------->" + it)
                adapter.submitList(it)
            }
        })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_high_scores, container, false)
    }  
}

class ScoreRepository(private val scoreDao: ScoreDao) {
   
    val allScores: Flow<List<Score>> = scoreDao.getScoresByDate()

    @Suppress("RedundantSuspendModifier")
    @WorkerThread
    suspend fun insert(score: Score) {
        scoreDao.insert(score)
    }
}

class GameViewModel(application: SimonSaysApplication) : AndroidViewModel(application) {

    val application = application
   
    val allScores: LiveData<List<Score>> = application.repository.allScores.asLiveData()

    var gameFinalScore = MutableLiveData<Int>()
    var lastColour = MutableLiveData<Int>()
    var gameOver = MutableLiveData<Boolean>()
    var useColours = true
    var useSounds = true
    var useNumbers = true
    private val colourList: MutableList<Int> = arrayListOf()
    private val selectedColourList: MutableList<Int> = arrayListOf()
    private var acceptBtnPress :Boolean = false

    fun insert(score: Score) = viewModelScope.launch(Dispatchers.IO) {
        application.repository.insert(score)
    }
....

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="0dp"
        android:layout_height="0dp"
        tools:listitem="@layout/recyclerview_item"
        android:padding="@dimen/big_padding"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:src="@drawable/ic_baseline_add_24"
        android:contentDescription="Add score"/>

</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

    标签: android android-recyclerview android-room


    【解决方案1】:

    更改这些代码行

            override fun areItemsTheSame(oldItem: Score, newItem: Score): Boolean {
                Log.i("ScoreListAdapter", "asking if items same ===  ----------->" )
                return oldItem === newItem
            }
    
            override fun areContentsTheSame(oldItem: Score, newItem: Score): Boolean {
                Log.i("ScoreListAdapter", "asking if items same == ----------->")
                return oldItem.score == newItem.score
            }
    

    到这里

            override fun areItemsTheSame(oldItem: Score, newItem: Score): Boolean {
                Log.i("ScoreListAdapter", "asking if items same ===  ----------->" )
                return oldItem.score == newItem.score
            }
    
            override fun areContentsTheSame(oldItem: Score, newItem: Score): Boolean {
                Log.i("ScoreListAdapter", "asking if items same == ----------->")
                return oldItem == newItem
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 2021-11-15
      • 2016-08-17
      • 1970-01-01
      相关资源
      最近更新 更多