Skip to content Skip to sidebar Skip to footer

How To Refresh View Of Previous Item Row View Of Recycle View

Hello guys hope you all are fine. I'm Developing an android app which will play different sounds of animals. I'm using Recycle View as you can see in the screenshot below. Now I'm

Solution 1:

Bellow sample works for a normal list data with RecyclerView.

  1. First we need to save clicked position then we have to apply notifyDataSetChanged().
  2. After that when list refreshing check your saved position with your actual bind position then apply changes what you need.

    public void onBindViewHolder(final MyViewHolder holder, final int position) {

        holder.tvGroupName.setText(list.get(position).getGroupName());
    
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
    
                // Save position in item click then refresh list
                pos = position;
                notifyDataSetChanged();
    
            }
        });
    
        // Once all items started refreshing check your save position with actual position then change text
        if (pos == position) {
            holder.tvGroupName.setText("Testing");
        }
    
    }
    

Hope this sample helpful..

And,

I also modified your class check this and hope it will work..

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
    private List<Animal> AnimalList;
    public Context ctx;
    public static int postionchange=-1;

    public static Tab1Birds t1;


    final int[] countLike = {0};
    //public static MediaPlayer mediaPlayer2 = new MediaPlayer();
    int pos;
    public class MyViewHolder extends RecyclerView.ViewHolder {
        public ImageView display;
        public TextView nameTextView;
        public ImageButton play,options,menubtn;
        public MyViewHolder(View view) {
            super(view);
            nameTextView = (TextView) view.findViewById(R.id.nameTextView);
            play=(ImageButton)view.findViewById(R.id.playbtn);
            options=(ImageButton)view.findViewById(R.id.menubtn);
            display=(ImageView)view.findViewById(R.id.imageview);
            menubtn = (ImageButton) view.findViewById(R.id.menubtn);
            //MediaPlayerClass.mediaPlayer= new MediaPlayer();
        }
    }
    public CustomAdapter(List<Animal> moviesList,Context ct) {
        this.AnimalList = moviesList;
        this.ctx=ct;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row_list, parent, false);
        return new MyViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        final Animal animal = AnimalList.get(position);

        final int[] previous = {position};
        holder.nameTextView.setText(animal.getName());
        holder.display.setImageResource(animal.getImageResource());
        //////////////////////////////////////////////////////////////////////////////////////////////////////////
        holder.options.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    if (MediaPlayerClass.mediaPlayer.isPlaying()) {
                        holder.play.setBackgroundResource(R.drawable.play_btn);
                        MediaPlayerClass.mediaPlayer.stop();
                    }
                } catch (Exception ex) {
                }
                Dialog dialog;
                final String[] items = {"SET AS RING TUNE", "SET AS MESSAGE TUNE", "SET AS ALARM TUNE"};
                final ArrayList itemsSelected = new ArrayList();
                final AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                builder.setTitle("OPTIONS");
                builder.setMultiChoiceItems(items, null,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int selectedItemId,
                                                boolean isSelected) {
                                if (isSelected) {
                                    itemsSelected.add(selectedItemId);
                                } else if (itemsSelected.contains(selectedItemId)) {
                                    itemsSelected.remove(Integer.valueOf(selectedItemId));
                                }
                            }
                        })
                        .setPositiveButton("Done!", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                Toast toast = Toast.makeText(ctx, "successfully selected", Toast.LENGTH_SHORT);
                                toast.show();
                                SparseBooleanArray CheCked = ((AlertDialog) dialog).getListView().getCheckedItemPositions();
                                String str = "";
                                if (CheCked.get(0)) {

                                    savering(animal.getSoundResource());
                                }
                                if (CheCked.get(1)) {
                                    savemsg(animal.getSoundResource());
                                }
                                if (CheCked.get(2)) {
                                    savealarm(animal.getSoundResource());
                                }
                                // if (CheCked.get(3)) {
                                // DatabaseHelper.save_bookmarks(itemsList.get(position).getitemName(), R.drawable.play_btn, itemsList.get(position).getItemTuneSt());
                                // Toast.makeText(ctx, "Item added to favourites", Toast.LENGTH_SHORT).show();

                                // }
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                            }
                        });
                dialog = builder.create();
                dialog.show();
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
        });


        // for animation
        // ///////////////////////////
        //animate(holder);//Function for animation
        //////////////////////////////

        holder.play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                pos=position;
                notifyDataSetChanged();                    

            }
        });

        if (pos == position){

            holder.play.setBackgroundResource(R.drawable.pause_btn);// present state
            MediaPlayerClass.play(animal.getSoundResource(),ctx);
            if(countLike[0] ==0)
            {
                countLike[0] =1;
            }else  if(countLike[0] ==1)
            {
                //if is playing then Pause
                if(MediaPlayerClass.mediaPlayer.isPlaying())
                    MediaPlayerClass.mediaPlayer.stop();

                t1.recyclerView.setAdapter(null);
                t1.customAdapter=new CustomAdapter(t1.animalList,ctx);
                t1.recyclerView.setAdapter(t1.customAdapter);


                holder.play.setBackgroundResource(R.drawable.play_btn); //sound stop show play button
                countLike[0] =2;
            }
            if(countLike[0] >1)
            {
                countLike[0] =0;
                holder.play.setBackgroundResource(R.drawable.play_btn); // click to play music, click again to stop music

            }
            //setOnCompletionListener
            MediaPlayerClass.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    holder.play.setBackgroundResource(R.drawable.play_btn);
                }
            });
            // MediaPlayerClass.mediaPlayer.start();
        }else {
            holder.play.setBackgroundResource(R.drawable.play_btn);
        }
    }
    @Override
    public int getItemCount() {
        return AnimalList.size();
    }
    //animation
    public void animate(RecyclerView.ViewHolder viewHolder) {
        final Animation animAnticipateOvershoot = AnimationUtils.loadAnimation(ctx, R.anim.bounce_interpolator);
        viewHolder.itemView.setAnimation(animAnticipateOvershoot);
    }

}

@Rajesh


Solution 2:

This question is similar to

Multiple YouTubePlayerFragments inside a Horizontal ScrollView - all the players display the last loaded video

You want to set play & pause icon to your list item depending on if sound file linked to that item is playing or not.

  // Set a global variable to keep track of which list item is playing.
  // if it is -1 then no sound is playing
    private int lastPosition = 0;

Now you need to add isPlaying variable to keep in your audio model

public class VideoModel { 

    private String audioURL;
    private String imageURL;
    private boolean isPlaying;

    public VideoModel(String audioURL, boolean isSelected,String imageURL) {
        this.videoURL = videoURL;
        this.isPlaying = isSelected;
    } 

    public boolean isPlaying() { 
        return isPlaying;
    } 

    public void setPlaying(boolean playing) {
        isPlaying = playing;
    } 

    /** 
     * @return Audio URL 
     */ 
    public String getAudioURL() {
        return audioURL;
    } 

    /** 
     * @return Thumbnail of Animal
     */ 
    public String getImageURL() {
        return imageURL;
    } 
} 

Now when user tap on any item in your list you need to update last playing item and assign now playing item to last playing item

 videoGridAdapter.setOnCardClickListner(new VideoGridAdapter.OnCardClickListner() { 
            @Override 
            public void OnCardClicked(View view, int position) {

                //Make Lats Tapped item playing false 
                listOfAudio.get(lastPosition).setPlaying(false); 

                //Make current Tapped item playing true 
                listOfAudio.get(position).setPlaying(true);

                // update pointer  current tapped audio
                lastPosition = position;

                //LET RCYCLERVIEW ADAPTER DO THE MAGIC 
                videoGridAdapter.notifyDataSetChanged(); 
            } 
        }); 

You need to manage hide show logic in adapter

 // Replace the contents of a view (invoked by the layout manager) 
    @Override 
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        VideoViewHolder videoHolder = (VideoViewHolder) holder;

        if (VideoGridActivity.listOfAudio.get(position).isPlaying()) {

            //Playing Video :- Show Pause Button and hide play button 
            ((VideoViewHolder) holder).getPauseButton().setVisibility(View.VISIBLE);
            ((VideoViewHolder) holder).getPlayButton().setVisibility(View.GONE);

          // Play sound and do other stuff


        } else { 

            //Not playing make Hide Pause Button and SHow Play button
            ((VideoViewHolder) holder).getPauseButton().setVisibility(View.GONE);
            ((VideoViewHolder) holder).getPlayButton().setVisibility(View.VISIBLE);

        } 
       }

This is a pseudo code but you got an idea how to do this. Hope it helps.


Solution 3:

I don't quite understand your flow. But I can give you a little hint.

You have 'AnimalList '

try to use notifyItemChanged(int position, Object payload);
and add someState variable(boolean) for determining which item is playing now. like below.

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
    final Animal animal = AnimalList.get(position);
    if(animal.isPlayStatus()){
       playButton.setSelected(true); 
    }else{
       playButton.setSelected(false); 
    }
}


public class Animal {
    boolean playStatus;
        .
        .
        .

    public boolean isPlayStatus() {
        return playStatus;
    }

    public void setPlayStatus(boolean playStatus) {
        this.playStatus = playStatus;
    }
}



Animal item = AnimalList.get(somePosition);
item.setPlayStatus(true);
notifyItemChanged(somePosition, item);

or

Animal previousItem = AnimalList.get(somePosition);
Animal item = AnimalList.get(somePosition + 1);
previousItem.setPlayStatus(false);
item.setPlayStatus(true);
mAdapter.notifyItemRangeChanged(somePosition, somePosition + 1);

or

int index = 0;
for (Animal item : AnimalList) {
   if(somePosition == index ){
      item.setPlayStatus(true);
   }else{
      item.setPlayStatus(false);
   }
   index++;
}
notifyItemRangeChanged(0, AnimalList.size()); // or 
notifyDatasetChanged();

Post a Comment for "How To Refresh View Of Previous Item Row View Of Recycle View"