【问题标题】:RecyclerView item to show the same background color on scrollingRecyclerView 项目在滚动时显示相同的背景颜色
【发布时间】:2021-06-11 04:01:01
【问题描述】:

我是 android 新手,我的回收站视图有问题。我希望使用随机颜色作为个人资料图像背景,但是当我上下滑动几次时颜色会不断变化,我希望每个项目都保持特定的颜色。请问我怎样才能做到这一点。这是我为随机化颜色所做的:

private fun changeClientProfileBackgroundColor ():Drawable?{val colorDrawables = arrayOf(
        R.drawable.client_list_background_color_drawable_1,
        R.drawable.client_list_background_color_drawable_2,
        R.drawable.client_list_background_color_drawable_3,
        R.drawable.client_list_background_color_drawable_4,
        R.drawable.client_list_background_color_drawable_5,
        R.drawable.client_list_background_color_drawable_6 )return ContextCompat.getDrawable(
        context!!, colorDrawables[(Math.random() * 5).roundToInt()])}



binding.clientHomeImageProfileColorBackground.background =
                changeClientProfileBackgroundColor()

Image of the recycler view with the background random colors

【问题讨论】:

    标签: android android-studio kotlin android-recyclerview


    【解决方案1】:

    如果您的适配器视图不稳定,请尝试在 recyclerview 适配器中使用getItemViewType

    在 stackoverflow 中查看上一个问题以获得更多参考。

    Recyclerview Changing Items During Scroll

    【讨论】:

      【解决方案2】:

      要在每个项目中设置随机背景颜色或图像,请按照此示例进行操作。这个例子使用背景颜色,但如果你想要图像,仍然是相同的过程。

      @Override
         public void onBindViewHolder(MyViewHolder viewHolder, int i) {
            studentData data=studentDataList.get(i);
            Random rnd = new Random();
            int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
            viewHolder.parent.setBackgroundColor(currentColor);
            viewHolder.name.setText(data.name);
            viewHolder.age.setText(String.valueOf(data.age));
         }
      

      This tutorial explain in details the procedure

      【讨论】:

      • 嗨@codewithbawo,如果它有效,请投票并将其标记为已回答的问题,以帮助其他用户看到此答案。
      • 我是新来的,我需要 15 声望才能投票。谢谢
      猜你喜欢
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      相关资源
      最近更新 更多