Reputation: 1747
I have a RecyclerView. Each row has a play button, textview and Progressbar. when click on the play button have to play audio from my sdcard and have to progress Progressbar The problem is when i scroll down the recyclerview change the Progressbar in next row.means I can fit 5 items on the screen at once. When I scroll to the 6th, 6th row seekbar changes suddenly.
public class ListAdapter extends RecyclerView.Adapter {
private List<Historyitem> stethitems;
public Context mContext;
public Activity activity;
public Handler mHandler;
static MediaPlayer mPlayer;
static Timer mTimer;
public ListAdapter(Activity activity,Context mContext,List<Historyitem> stethitems) {
this.stethitems = stethitems;
this.mContext = mContext;
this.activity = activity;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View rootView = LayoutInflater.
from(mContext).inflate(R.layout.stethoscopeadapteritem, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
rootView.setLayoutParams(lp);
mHandler = new Handler();
return new MyViewHolder(rootView);
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, int position) {
final Historyitem dataItem = stethitems.get(position);
final MyViewHolder myViewHolder = (MyViewHolder) viewHolder;
myViewHolder.progressplay.setProgress(0);
myViewHolder.stethdatetime.setText(dataItem.getReported_Time());
myViewHolder.stethhosname.setText(dataItem.getdiv());
if(dataItem.getPatient_Attribute().replaceAll(" ","").equals("")){
myViewHolder.stethdoctorname.setText(dataItem.getunit());
} else {
myViewHolder.stethdoctorname.setText(dataItem.getPatient_Attribute());
}
myViewHolder.stethstreamplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FileDownload(dataItem.getmsg(),
myViewHolder.progressplay);
}
});
}
@Override
public int getItemCount() {
return stethitems.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
final CustomTextRegular stethdatetime;
final CustomTextView stethhosname;
final CustomTextBold stethdoctorname;
final ImageButton stethstreamplay;
final NumberProgressBar progressplay;
public MyViewHolder(View itemView) {
super(itemView);
stethdatetime = (CustomTextRegular)
itemView.findViewById(R.id.stethdatetime);
stethhosname = (CustomTextView)
itemView.findViewById(R.id.stethhosname);
stethdoctorname = (CustomTextBold)
itemView.findViewById(R.id.stethdoctorname);
stethstreamplay = (ImageButton)
itemView.findViewById(R.id.stethstreamplay);
progressplay= (NumberProgressBar)
itemView.findViewById(R.id.progressplay);
}
}
public void FileDownload(final String downloadpath,
final NumberProgressBar progressplay) {
new AsyncTask<NumberProgressBar, Integer, NumberProgressBar>() {
NumberProgressBar progress;
@Override
protected void onPreExecute() {
super.onPreExecute();
try {
if(mPlayer!=null){
mPlayer.stop();
}
}catch (Exception e){
}
try {
if(mTimer != null){
mTimer.purge();
mTimer.cancel();
}
}catch (Exception e){
}
}
@Override
protected NumberProgressBar doInBackground(NumberProgressBar... params) {
int count;
progress = progressplay;
try {
final List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("pid",id));
URL url = new URL(Config.requestfiledownload + "?path=" +
downloadpath);
URLConnection connection = url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() +
"record.wav");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return progress;
}
@Override
protected void onPostExecute(final NumberProgressBar numberProgressBar) {
super.onPostExecute(numberProgressBar);
try {
StartMediaPlayer(numberProgressBar);
} catch (Exception e){
e.printStackTrace();
}
}
}.execute();
}
public void StartMediaPlayer(final NumberProgressBar progressbar){
Uri playuri = Uri.parse("file:///sdcard/record.wav");
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.reset();
try {
mPlayer.setDataSource(mContext, playuri);
} catch (IllegalArgumentException e) {
} catch (SecurityException e) {
} catch (IllegalStateException e) {
} catch (Exception e) {
}
try {
mPlayer.prepare();
} catch (Exception e) {
}
mPlayer.start();
progressbar.setMax(mPlayer.getDuration());
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if(mPlayer!=null) {
mPlayer.release();
progressbar.setProgress(0);
}
if(mTimer != null){
mTimer.purge();
mTimer.cancel();
}
}
});
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
progressbar.setProgress(mPlayer.getCurrentPosition());
}
});
}
},0,500);
}}
Upvotes: 100
Views: 106350
Reputation: 93
Since we know that kotlin synthetic is now deprecating from kotlin 1.8 onwards. Discontinuing Kotlin synthetics for views And if you are using view binding for it's alternative, then this Viewbinding on RecyclerView may cause this problem. In the adapter class i was initializing my view on onCreateViewHolder and passing binding object to our viewHolder class
binding = parent.viewBinding(ItemBinding::inflate)
return MyViewViewHolder(binding.root)
But later I found issue that items are moving here & there on scrolling, so I passed view using inflator.
val itemView: View = LayoutInflater.from(parent.context)
.inflate(R.layout.list_item, parent, false)
return MyViewViewHolder(itemView)
And on onBindViewHolder i accessed each object by findViewById<YourView>
.
This solved my problem.
Upvotes: 0
Reputation: 81
Just put you recylerView in a NestedScroll View in your xml and add the property nestedScrollingEnabled = false.
And on your adapter onBindViewHolder add this line
final MyViewHolder viewHolder = (MyViewHolder)holder;
Use this viewHolder object with your views to setText or do any kind of Click events.
e.g viewHolder.txtSubject.setText("Example");
Upvotes: 3
Reputation: 5644
Please try this
If you are using ListView
- override the following methods.
@Override
public int getViewTypeCount() {
return getCount();
}
@Override
public int getItemViewType(int position) {
return position;
}
If you are using RecyclerView
- override only getItemViewType()
method.
@Override
public int getItemViewType(int position) {
return position;
}
Upvotes: 288
Reputation: 2136
Add setHasStableIds(true);
in your adapter constructor and Override these two methods in adapter. It also worked if anyone using a RecyclerView
inside a ViewPager
which is also inside a NestedScrollView
.
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position;
}
Upvotes: 69
Reputation: 81
If your recyclerview ViewHolder has more logic or has a different different view then you should try:
**order_recyclerView.setItemViewCacheSize(x);**
where x is the size of the list. The above works for me, I hope it works for you too.
Upvotes: 8
Reputation: 598
Override the method getItemViewType in adapter. in kotlin use
override fun getItemViewType(position: Int): Int {
return position
}
Upvotes: 2
Reputation: 334
When we are changing RecyclerView
items dynamically (i.e. when changing background color of a specific RecyclerView
item), it could change appearance of the items in unexpected ways when scrolling due to the nature of how RecyclerView
reuse its items.
However to avoid that it is possible to use android.support.v4.widget.NestedScrollView
wrapped around the RecyclerView
and letting the NestedScrollView
handle the scrolling.
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
And then in the code you can disable nested scrolling for the RecyclerView
to smooth out scrolling by letting only the NestedScrollView
to handle scrolling.
ViewCompat.setNestedScrollingEnabled(recyclerView, false);
Upvotes: 4
Reputation: 129
recyclerview.setItemViewCacheSize(YourList.size());
Upvotes: 12
Reputation: 150
I have faced the same problem while I was trying to implement a recyclerview that contains a edittex and a checkbox as a row elements. I solved the scrolling value changing problem just by adding the following two lines in the adapter class.
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position;
}
I hope it will be a possible solution. Thanks
Upvotes: 14
Reputation: 3871
This line changes progress to 0 on each bind
myViewHolder.progressplay.setProgress(0);
Save its state somewhere then load it in this same line.
Upvotes: 0
Reputation: 37
I had the similar issue and searched alot for the right answer. Basically it is more of a design of recycler view that it updates the view on the scroll because it refreshes the view.
So all you need to do is at the bind time tell it not to refresh it.
This is how your onBindViewHolder should look like
@Override
@SuppressWarnings("unchecked")
public void onBindViewHolder(final BaseViewHolder holder, final int position) {
holder.bind(mList.get(position));
// This is the mighty fix of the issue i was having
// where recycler view was updating the items on scroll.
holder.setIsRecyclable(false);
}
Upvotes: 0
Reputation: 5121
try this
@Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) { LinearSmoothScroller linearSmoothScroller =
new LinearSmoothScroller(recyclerView.getContext()) {
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return LinearLayoutManager.this
.computeScrollVectorForPosition(targetPosition);
}
}; linearSmoothScroller.setTargetPosition(position); startSmoothScroll(linearSmoothScroller); }
Upvotes: 0
Reputation: 1
Why don't you try like this,
HashMap<String, Integer> progressHashMap = new HashMap<>();
//...
if(!progressHashMap.containsKey(downloadpath)){
progressHashMap.put(downloadpath, mPlayer.getCurrentPosition());
}
progressbar.setProgress(progressHashMap.get(downloadpath));
Upvotes: 0
Reputation: 2493
I had the same problem while handle a lot of data , it works with 5 because it renders the five elements that are visible on the screen but that gives prob with more elements. The thing is ..
Sometimes RecyclerView and listView just skips Populating Data. In case of RecyclerView binding function is skipped while scrolling but when you try and debug the recyclerView adapter it will work fine as it will call onBind every time , you can also see the official google developer's view The World of listView. Around 20 min -30 min they will explain that you can never assume the getView by position will be called every time.
so, I will suggest to use
RecyclerView DataBinder created by satorufujiwara.
or
RecyclerView MultipleViewTypes Binder created by yqritc.
These are other Binders available if you find those easy to work around .
This is the way to deal with MultipleView Types or if you are using large amount of data . These binders can help you just read the documentation carefully that will fix it, peace!!
Upvotes: 0
Reputation: 1996
This is the expected behaviour of recyclerView. Since the view is recycled your items may get into random views. To overcome this you have to specify which item is put into which kind of view by yourself. This information can be kept in a SparseBooleanArray. what you can do is create a SparseBooleanArray in your adapter like this
SparseBooleanArray selectedItems = new SparseBooleanArray();
whenever your view changes, do:
selectedItems.put(viewItemIndex,true);
Now in your onBindViewHolder do
if(selectedItems.get(position, false)){
//set progress bar of related to the view to desired position
}
else {
//do the default
}
This is the basic to solve your problem. You can adjust this logic to any kind of similar problem in recyclerView.
Upvotes: -2
Reputation: 20221
As the name implies, the views in a RecyclerView
are recycled as you scroll down. This means that you need to keep the state of each item in your backing model, which in this case would be a Historyitem
, and restore it in your onBindViewHolder
.
1) Create position, max, and whatever other variables you need to save the state of the ProgressBar
in your model.
2) Set the state of your ProgressBar
based on the data in your backing model; on click, pass the position of the item to your FileDownload
/StartMediaPlayer
methods.
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, int position) {
final Historyitem dataItem = stethitems.get(position);
final MyViewHolder myViewHolder = (MyViewHolder) viewHolder;
myViewHolder.progressplay.setMax(dataItem.getMax());
myViewHolder.progressplay.setProgress(dataItem.getPosition());
...
myViewHolder.stethstreamplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FileDownload(dataItem.getmsg(), position);
}
});
3) Update the progress bar by updating the backing model and notifying that it was changed.
stethitems.get(position).setPosition(mPlayer.getCurrentPosition());
notifyItemChanged(position);
Upvotes: 37