Periodically updating child updates ui

I have a recyclerView of elements that (among other things) contain a timeStamp of the duration of a game derived from WS. To show the duration of the match, I have to get the current time value, fill the mat and convert it to a readable format (for example, 5 minutes 5 seconds). Only some of the species need to be updated.

Each child should be updated every xxx seconds.

  • In my first aproach, a list of objects bound to the view that needed to be updated was created. On my snippet, I declare a handler and call notifyItemChanged (position) for each object in the list. Each time the handler calls notifyItemChanged, the whole view is re-displayed, and there is a slight blinking effect. I don't want this to happen, so my second approach was to change the TextView of each child that needs to be updated. Here is the code:

    @Override public void onBindViewHolder(MyViewHolder holder, int position) { if (needsUpdate) { holder.startRepeatingTask(); } else { holder.stopRepeatingTask(); } } class MyViewHolder extends RecyclerView.ViewHolder { private final int mHandlerInterval = 6000; private Handler mHandler; private Runnable mStatusChecker; public MyViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); mHandler = new Handler(); mStatusChecker = new Runnable() { @Override public void run() { String gameStatusToPrint = current.getGameStatusToPrint(); gameStatus.setText(gameStatusToPrint); mHandler.postDelayed(mStatusChecker, mHandlerInterval); } }; } public void startRepeatingTask() { mStatusChecker.run(); } public void stopRepeatingTask() { mHandler.removeCallbacks(mStatusChecker); } } 

I am not sure if this is the best approach and a recommendation is needed for this.

+1
source share
1 answer

As ViewHolder is redesigned by RecyclerView. You need to make sure that you maintain stability between the "current game" and the item listed. Despite this, I think your decision is in order.

Here's the fix for this:

 @Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.game = mGameList.get(position); if (needsUpdate) { holder.startRepeatingTask(); } else { holder.stopRepeatingTask(); } } class MyViewHolder extends RecyclerView.ViewHolder { private final int mHandlerInterval = 6000; private Handler mHandler; private Runnable mStatusChecker; public Game game; public MyViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); mHandler = new Handler(); mStatusChecker = new Runnable() { @Override public void run() { String gameStatusToPrint = game.getGameStatusToPrint(); gameStatus.setText(gameStatusToPrint); mHandler.postDelayed(mStatusChecker, mHandlerInterval); } }; } public void startRepeatingTask() { mStatusChecker.run(); } 
+1
source

All Articles