如何刷新回收视图的上一个项目行视图 [英] how to refresh view of previous item row view of recycle view

查看:109
本文介绍了如何刷新回收视图的上一个项目行视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,希望大家一切都好. 我正在开发一个可播放不同动物声音的android应用.

我正在使用回收视图,如下面的屏幕快照所示.现在,我遇到了一个问题,我在行内有一个播放按钮,每当我播放项目0或在视图中向我显示暂停选项的任何位置时,该按钮都在播放动物的声音.但是,每当我单击下一个项目1或其他任何项目时,它都不会更改上一个项目0的图像.

我正在通过使用以下代码刷新适配器列表来做到这一点! 但我认为这不是一个好习惯.

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

我尝试使用notifyItemChanged(oldPosition)之类的所有方法,但仍然没有得到我想要的结果.

请建议我解决此问题的合适方法?我是android的新手,我有一个想法要获取最后一个项目的视图并先保存它,然后再获得该视图并在上一个列表按钮上设置默认的图像播放,但是我不知道该怎么做?/p>

这是我的自定义适配器"代码.

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=0;
    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();
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
        });
        pos=position;

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

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

                if(postionchange==-1)
                {
                    postionchange=position;
                }
                if(postionchange!=position)
                {
                    holder.play.setBackgroundResource(R.drawable.play_btn);
                }
                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();

                }
        });
    }
        @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);
    }

    //////////////////////////////////////////////////////////////////////////////////////////

}

这里是三星手机中的音乐播放器的示例. 每当我播放音乐时,它都会显示动画,当我播放下一首歌曲时,它会播放该歌曲,并停止上一首播放的音乐及其动画. 我知道如何停止媒体播放器,但是如何更改以停止动画或音乐库等?

解决方案

此问题类似于

水平ScrollView中的多个YouTubePlayerFragments-所有播放器都显示最后加载的视频

您要设置播放&将图标暂停到列表项,具体取决于链接到该项的声音文件是否正在播放.

  // 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;

现在您需要添加isPlaying变量以保留在音频模型中

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;
    } 
} 

现在,当用户点击列表中的任何项目时,您需要更新最后播放的项目并将当前正在播放的项目分配给最后播放的项目

 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(); 
            } 
        }); 

您需要管理适配器中的隐藏显示逻辑

 // 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);

        } 
       }

这是一个伪代码,但是您知道如何执行此操作.希望能帮助到你.

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 facing a problem, I have a play button inside my row which is playing the sound of the animal whenever I play sound from my item 0 or any position it shows me pause option inside view. But whenever I click on next item 1 or any other it's not changing the image of previous item 0.

I'm doing it by refreshing my list of adapter by using following code.! but I think its not a good practice.!

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

I tried using every thing like notifyItemChanged(oldPosition) but still havent got my desired result.!

Kindly suggest me a appropriate way to solve this? I'm new to android and I have one thought in mind to get view of last item and save it first then I get that view and set default image play on my previous list button but I don't know how to do this?

here is my code of Custom Adapter.!

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=0;
    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();
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
        });
        pos=position;

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

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

                if(postionchange==-1)
                {
                    postionchange=position;
                }
                if(postionchange!=position)
                {
                    holder.play.setBackgroundResource(R.drawable.play_btn);
                }
                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();

                }
        });
    }
        @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);
    }

    //////////////////////////////////////////////////////////////////////////////////////////

}

Here is an example of Music player In Samsung Mobiles.! When ever I play music it shows animation and when I play next song it play that song and stops the previous playing music and its animation.! I know how to stop media player but how to change stop that animation or music library etc.?

解决方案

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.

这篇关于如何刷新回收视图的上一个项目行视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆