Home > Software design >  Why does RecyclerView not reflect progress in circle ProgressBar correctly after scrolling?
Why does RecyclerView not reflect progress in circle ProgressBar correctly after scrolling?

Time:11-27

I am using a RecyclerView whose elements contain a circle ProgressBar.

progress_circle_yellow.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">


    <item
        android:bottom="0dp"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp">
        <shape android:shape="oval">
            <solid android:color="@color/progress_circle_background" />
            <stroke android:color="@color/black" />
        </shape>
    </item>
    <item>
        <shape android:shape="ring"
            android:innerRadiusRatio="999"
            android:thicknessRatio="2.5">
            <solid android:color="@color/progress_circle_yellow"/>
        </shape>
    </item>


</layer-list>

MainActivity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<String> titleNames = new ArrayList<>();

    for (int i = 0; i < 77; i  ) {
        titleNames.add("Title # " i);
    }

     progressDrawable = getResources().getDrawable(R.drawable.progress_circle_yellow);

    RecyclerView recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new MyRecyclerViewAdapter(this, titleNames);
    adapter.setClickListener(this);
    recyclerView.setAdapter(adapter);
}

When the RecyclerView is initially displayed, the progress is reflected correctly, but after scrolling, the progress stops being displayed correctly. enter image description here MyRecyclerViewAdapter

public void onBindViewHolder(ViewHolder holder, int position) {
    String title = mData.get(position);
    holder.myTextView.setText(title);
    holder.progressBar.setProgress(position);
    holder.progressBar.setProgressDrawable(MainActivity.progressDrawable);
}

How can this be fixed?

CodePudding user response:

It looks to me like you are using a static variable for the progress bar because you have the following line in the bind view holder code:

holder.progressBar.setProgressDrawable(MainActivity.progressDrawable);

This is the root of your problem since you have only on drawable for all your view holders. The seemingly random assignment of progress is just displaying the last value bound before the progress bar is drawn. The following will work better.

Remove the above line from your binding code and add the following to your view holder creation code:

LayerDrawable d = (LayerDrawable) ContextCompat.getDrawable(item.getContext(), R.drawable.progress_circle_yellow);
mProgressBar.setProgressDrawable(d);

This will give you different drawables for each view holder that can hold different progress values.

  • Related