在android中滚动RecyclerView时SeekBar进度发生变化

问题描述 投票:0回答:1

我正在开发一款类似于 What's Up 的聊天应用程序。我遇到的问题是我在回收器视图中有搜索栏和播放图标。当我单击播放符号时,将播放歌曲,并且搜索栏也会随之移动。到这里为止一切都运行良好。问题是,当我在播放某些歌曲时滚动 recyclerView 时,搜索栏的进度设置为自动结束。如果我再次滚动,搜索栏进度位置将根据歌曲持续时间更改。我不知道为什么会发生这种情况。有人有解决方案吗?预先感谢:)

public class ChatContentAdapter extends RecyclerView.Adapter implements Handler.Callback {
    private OnItemClickListener onItemClickListener;
    public Handler handler;
    private List<MessageInfo> messageInfoList = new ArrayList<>();
    List<ZIMGroupMemberInfo> memberList = new ArrayList<>();
    private Activity activity;
    Context context;
    String date = "";
    int count=0;
    boolean isPost = false;
    //boolean dateAvailable=false;
    String urlRegex = "^((https?|ftp)://|(www|ftp)\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$";
    GetRequestWithEditPostGetDetailsModel.Data postData ;
    BaseViewHolder baseViewHolder;
    private int playingPosition;
    MediaPlayer mediaPlayer;
    Uri audioPathUri;
     Handler uiUpdateHandler = new Handler(this::handleMessage);

    private float denseness;
    private int width;

    private static final int MSG_UPDATE_SEEK_BAR = 1845;
    public ChatContentAdapter (Activity activity,OnItemClickListener onItemClickListener){
        this.activity = activity;
        this.onItemClickListener = onItemClickListener;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        if (ChatItemType.CHAT_ITEM_TYPE_RIGHT.value == viewType) {
            viewHolder = new ChatRightViewHolder(parent, onItemClickListener, activity);
        } else if (ChatItemType.CHAT_ITEM_TYPE_LEFT.value == viewType) {
            viewHolder = new ChatLeftViewHolder(parent, onItemClickListener, activity);
        } else if (ChatItemType.CHAT_ITEM_TYPE_CENTER.value == viewType){
            viewHolder = new ChatCenterViewHolder(parent,activity);
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        holder.itemView.setTag(position);
        MessageInfo messageInfo = messageInfoList.get(position);
        Log.d("TAG", "onBindViewHolder: "+messageInfo.isPlay());


        if(HomeActivity.homeActivity.cacheRepository.getMessageDate().equals("0")){
            HomeActivity.homeActivity.cacheRepository.saveMessageDate(Utilities.INSTANCE.getDateinYmd(messageInfo.getZIMMessage().getTimestamp()));
        }

        if (holder instanceof ChatLeftViewHolder) {
            ChatLeftViewHolder chat = (ChatLeftViewHolder) holder;
            chat.setMessageInfo(messageInfo,date,memberList,position,postData,messageInfoList.size());
            chat.seekBar.setProgress(messageInfoList.get(position).getSeekBarProgressValue());
            Log.i("TAG", "onBindViewHolder: " +messageInfoList.get(position).getSeekBarProgressValue() );
            if (messageInfo.isPlay()){
                chat.ivPlayPause.setImageResource(R.drawable.ic_pause);

            }else {
                chat.ivPlayPause.setImageResource(R.drawable.ic_play);
                chat.seekBar.setProgress(0);
                chat.txtProcess.setText("00:00:00"+ "/"+ "00:00:00");
            }

            chat.ivPlayPause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SDKManager.sharedInstance().downloadMediaFile((ZIMMediaMessage) messageInfo.getZIMMessage(), ZIMMediaFileType.ORIGINAL_FILE, new ZIMMediaDownloadedCallback() {
                        @Override
                        public void onMediaDownloaded(ZIMMediaMessage message, ZIMError errorInfo) {
                           String path = new File(message.getFileLocalPath()).getAbsolutePath();
                            if (!path.isEmpty()){
                               Uri audioPath = Uri.parse(path);
                               setPlayer(audioPath,position,chat);
                            }
                        }

                        @Override
                        public void onMediaDownloadingProgress(ZIMMediaMessage message, long currentFileSize, long totalFileSize) {
                            AppLogger.getInstance().d("[%s] [onMediaDownloadingProgress] [currentFileSize:%d, totalFileSize:%d, message: %s]","TAG", currentFileSize, currentFileSize, message.getMessageID());
                        }
                    });

                }
            });

            chat.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @SuppressLint("ResourceAsColor")
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                    if (fromUser) {
                        if (mediaPlayer != null) {
                            mediaPlayer.seekTo(progress);
                            Log.i("TAG", "onProgressChanged: "+ progress);
                        seekBar.setMax(mediaPlayer.getDuration()/1000);

                        }

                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    if (((Activity)context)  != null) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                chat.imgPause.setVisibility(View.GONE);
                                chat.ivPlayPause.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    if (mediaPlayer != null) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                chat.ivPlayPause.setVisibility(View.GONE);
                                chat.imgPause.setVisibility(View.VISIBLE);
                                try {
                                    mediaPlayer.start();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });

                    }
                }

            });
        } else if (holder instanceof ChatRightViewHolder) {
            ChatRightViewHolder chat = (ChatRightViewHolder) holder;

            chat.setMessageInfo(messageInfo, date,memberList,position,postData, messageInfoList.size());

            chat.seekBar.setProgress(messageInfoList.get(position).getSeekBarProgressValue());

            if (messageInfo.isPlay()){
                chat.ivPlayPause.setImageResource(R.drawable.ic_pause);

            }else {
                chat.ivPlayPause.setImageResource(R.drawable.ic_play);
                chat.seekBar.setProgress(0);
                chat.txtProcess.setText("00:00:00"+ " / " + "00:00:00");
            }
            chat.ivPlayPause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SDKManager.sharedInstance().downloadMediaFile((ZIMMediaMessage) messageInfo.getZIMMessage(), ZIMMediaFileType.ORIGINAL_FILE, new ZIMMediaDownloadedCallback() {
                        @Override
                        public void onMediaDownloaded(ZIMMediaMessage message, ZIMError errorInfo) {
                            String path = new File(message.getFileLocalPath()).getAbsolutePath();
                            if (!path.isEmpty()){
                                Uri audioPath = Uri.parse(path);
                                setPlayerRight(audioPath,position, chat);
                            }
                        }

                        @Override
                        public void onMediaDownloadingProgress(ZIMMediaMessage message, long currentFileSize, long totalFileSize) {
                            AppLogger.getInstance().d("[%s] [onMediaDownloadingProgress] [currentFileSize:%d, totalFileSize:%d, message: %s]", "TAG", currentFileSize, currentFileSize, message.getMessageID());
                        }
                    });
                }
            });

            chat.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (((Activity) context) != null) {
                        if (fromUser) {
                            if (mediaPlayer!=null){
                                mediaPlayer.seekTo(progress );
                                Log.i("TAG", "run: " + progress);
                                seekBar.setMax(mediaPlayer.getDuration()/1000);
                            }
                        }
                    }
                }
                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                    if (((Activity)context)  != null) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                chat.ivPlayPause.setVisibility(View.GONE);
//                                chat.imgPause.setVisibility(View.VISIBLE);

                            }
                        });
                    }
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    if (mediaPlayer != null) {
                    if (((Activity)context)  != null) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                chat.ivPlayPause.setVisibility(View.GONE);
//                                chat.imgPause.setVisibility(View.VISIBLE);
                                try {
                                    mediaPlayer.start();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    }
                }
            });
      }
        }

    }

    private void updateForRightViewHolder(MediaPlayer mediaPlayer, ChatRightViewHolder chat, SeekBar seekBar, Context context) {

        if (mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition() > 100) {
            chat.txtProcess.setText(convertSecondsToHMmSs(mediaPlayer.getCurrentPosition() / 1000) + " / " + convertSecondsToHMmSs(this.mediaPlayer.getDuration() / 1000));
//            seekBar.setProgress(mediaPlayer.getCurrentPosition());
            Log.i("TAG", "updateForRightViewHolder: " + playingPosition  + mediaPlayer.getCurrentPosition());
            onItemClickListener.seekBarProgressValue(playingPosition,mediaPlayer.getCurrentPosition());

        }else {
            chat.txtProcess.setText(convertSecondsToHMmSs(mediaPlayer.getDuration() / 1000));
//            seekBar.setProgress(mediaPlayer.getCurrentPosition());
            Log.i("TAG", "updateForRightViewHolder: " + playingPosition  + mediaPlayer.getCurrentPosition());
            onItemClickListener.seekBarProgressValue(playingPosition,mediaPlayer.getCurrentPosition());
        }
        Handler handler = new Handler();

        try{
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try{
                        if (ChatContentAdapter.this.mediaPlayer.getCurrentPosition() > -1) {
                            try {
                                updateForRightViewHolder(mediaPlayer,chat, seekBar, context);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            };
//            handler.postDelayed(runnable, 100);
            seekBar.postDelayed(runnable,100);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void setPlayerRight(Uri audioPath, int position, ChatRightViewHolder chat) {
        if (position == playingPosition){
            if (mediaPlayer.isPlaying()) {
                messageInfoList.get(position).setPlay(false);
                mediaPlayer.pause();
                chat.ivPlayPause.setImageResource(R.drawable.ic_play);
            } else {
                messageInfoList.get(position).setPlay(true);
                mediaPlayer.start();
                chat.ivPlayPause.setImageResource(R.drawable.ic_pause);
            }

        }else {
            if (playingPosition != -1) {
                onItemClickListener.getPosition(playingPosition);
            }
            playingPosition = position;
            if (mediaPlayer != null) {
                chat.ivPlayPause.setImageResource(R.drawable.ic_play);
                mediaPlayer.release();
            }
            startRightMediaPlayer(audioPath, chat);
            messageInfoList.get(position).setPlay(true);
            chat.ivPlayPause.setImageResource(R.drawable.ic_pause);
        }
    }

    private void startRightMediaPlayer(Uri audioPath, ChatRightViewHolder chat) {
        mediaPlayer = MediaPlayer.create(getApplicationContext(),audioPath);

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                chat.seekBar.setMax(mp.getDuration());
                chat.txtProcess.setText("00:00:00/"+convertSecondsToHMmSs(mp.getDuration() / 1000));
            }
        });

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                releaseMediaPlayer();
            }
        });
        mediaPlayer.start();
        updateForRightViewHolder(mediaPlayer, chat, chat.seekBar, context);
    }



    private void setPlayer(Uri audioPath, int position, ChatLeftViewHolder chat) {
        if (position == playingPosition){

            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                messageInfoList.get(position).setPlay(false);
                chat.ivPlayPause.setImageResource(R.drawable.ic_play);
            } else {
                messageInfoList.get(position).setPlay(true);
                mediaPlayer.start();
                chat.ivPlayPause.setImageResource(R.drawable.ic_pause);
            }
        }else {
            if (playingPosition != -1) {
                onItemClickListener.getPosition(playingPosition);
            }
            playingPosition = position;
            if (mediaPlayer != null) {
                chat.ivPlayPause.setImageResource(R.drawable.ic_play);

                mediaPlayer.release();
            }

            startMediaPlayer(audioPath,chat);
            messageInfoList.get(position).setPlay(true);
            chat.ivPlayPause.setImageResource(R.drawable.ic_pause);
        }
    }

    private void startMediaPlayer(Uri audioPathUri, ChatLeftViewHolder chat) {
        mediaPlayer = MediaPlayer.create(getApplicationContext(),audioPathUri);
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                chat.seekBar.setMax(mp.getDuration());
                chat.txtProcess.setText("00:00:00/"+convertSecondsToHMmSs(mp.getDuration() / 1000));
            }
        });

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                chat.ivPlayPause.setImageResource(R.drawable.ic_play);
                releaseMediaPlayer();
            }
        });
            mediaPlayer.start();
            update(mediaPlayer, chat, chat.seekBar, context);

        chat.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                if (((Activity) context) != null) {
                    if (fromUser) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mediaPlayer != null) {
                                    mediaPlayer.seekTo(progress);
                                    Log.i("TAG", "run: " + progress);
                                }
                            }
                        });

                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

                    if (((Activity)context)  != null) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                chat.ivPlayPause.setVisibility(View.GONE);
//                                chat.imgPause.setVisibility(View.VISIBLE);
                            }
                        });
                    }

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mediaPlayer != null) {
                if (((Activity)context)  != null) {
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            chat.ivPlayPause.setVisibility(View.GONE);
//                            chat.imgPause.setVisibility(View.VISIBLE);
                            try {
                                mediaPlayer.start();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                }
            }
        });
        }
    private void update(MediaPlayer mediaPlayer, ChatLeftViewHolder chat, SeekBar seekBar, Context context) {

        if (mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition() > 100) {
            chat.txtProcess.setText(convertSecondsToHMmSs(mediaPlayer.getCurrentPosition() / 1000) + " / " + convertSecondsToHMmSs(this.mediaPlayer.getDuration() / 1000));
//            seekBar.setProgress(mediaPlayer.getCurrentPosition());
            onItemClickListener.seekBarProgressValue(playingPosition,mediaPlayer.getCurrentPosition());

        }else {
            chat.txtProcess.setText(convertSecondsToHMmSs(mediaPlayer.getDuration() / 1000));
//            seekBar.setProgress(mediaPlayer.getCurrentPosition());
        }
        Handler handler = new Handler();

        try{
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try{
                        if (ChatContentAdapter.this.mediaPlayer.getCurrentPosition() > -1) {
                            try {
                                update(mediaPlayer,chat, seekBar, context);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            };
            handler.postDelayed(runnable, 100);
//            seekBar.postDelayed(runnable,500);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private static String convertSecondsToHMmSs(int seconds) {
        long s = seconds % 60;
        long m = (seconds / 60) % 60;
        long h = (seconds / (60 * 60)) % 24;
        return String.format("%02d:%02d:%02d", h,m,s);
    }

    public void releaseMediaPlayer() {
//        if (null != baseViewHolder) {
//            updateNonPlayingView(baseViewHolder);
//        }

        mediaPlayer.release();

        mediaPlayer = null;
        playingPosition = -1;
    }

    public void updateNonPlayingView(BaseViewHolder holder) {
        holder.ivPlayPause.setImageResource(R.drawable.ic_play_arrow);
        holder.seekBar.setMax(mediaPlayer.getDuration());
        holder.seekBar.setProgress(mediaPlayer.getCurrentPosition());
        holder.seekBar.setEnabled(true);
        if (mediaPlayer.isPlaying()){
            uiUpdateHandler.sendEmptyMessageDelayed(MSG_UPDATE_SEEK_BAR, 100);
            holder.ivPlayPause.setVisibility(View.GONE);
            holder.imgPause.setVisibility(VISIBLE);
        }else {
            uiUpdateHandler.removeMessages(MSG_UPDATE_SEEK_BAR);
            holder.imgPause.setVisibility(View.GONE);
            holder.ivPlayPause.setVisibility(VISIBLE);
        }
    }

     public   void stopPlayer(){
        if (null != mediaPlayer) {
            releaseMediaPlayer();
        }

    }




    @Override
    public int getItemViewType(int position) {
        return messageInfoList.get(position).getType().value;
    }





    @Override
    public int getItemCount() {
        return messageInfoList.size();
    }



    @Override
    public long getItemId(int position) {
        return messageInfoList.get(position).hashCode();
    }




//    @Override
//    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
//        super.onAttachedToRecyclerView(recyclerView);
//        recyclerView.smoothScrollToPosition(messageInfoList.size()-1);
//    }

    public void add(MessageInfo messageInfo) {
        messageInfoList.add(0,messageInfo);
    }


    public void setPlayPause(int pos){
        messageInfoList.get(pos).setPlay(false);
        notifyItemChanged(pos);
    }

    public void setSeekBar(int playingPosition ,int progressValue){
        messageInfoList.get(playingPosition).setSeekBarProgressValue(progressValue);
        notifyItemChanged(playingPosition);
        Log.i("TAG", "setSeekBarAdapter: " + playingPosition + progressValue);
    }

    public void addMessageToBottom(MessageInfo messageInfo){
        messageInfoList.add(messageInfo);
    }

    public void delete(MessageInfo info) {
        MessageInfo tempInfo = info;
        for (MessageInfo c : messageInfoList) {
            if (c.getZIMMessage().getMessageID() == info.getZIMMessage().getMessageID()) {
                tempInfo = c;
            }
        }
        messageInfoList.remove(tempInfo);
    }

    public void delete(long messageId) {
        MessageInfo tempInfo = null;
        int position = 0;
        for (int i = 0; i < messageInfoList.size(); i++) {
            if (messageInfoList.get(i).getZIMMessage().getMessageID() == messageId) {
                tempInfo = messageInfoList.get(i);
                position = i;
                break;
            }
        }

        if (tempInfo!=null){
            messageInfoList.remove(tempInfo);
            notifyItemRemoved(position);
        }
    }

    public void clearInfo() {
        messageInfoList.clear();
    }

    public MessageInfo getMessage(int index) {
        if (messageInfoList != null && messageInfoList.size() > 0) {
            return messageInfoList.get(index);
        }
        return null;
    }

    public void set(MessageInfo info){
        int position = 0;
        for (int i = 0; i < messageInfoList.size(); i++) {
            if (messageInfoList.get(i).getZIMMessage().getLocalMessageID() == info.getZIMMessage().getLocalMessageID()) {
                position = i;
                break;
            }
        }
        if (position!=0){
            messageInfoList.set(position,info);
            notifyItemChanged(position);
        }

    }

    public void updateMessageWhenDiffSentStatus(MessageInfo info){
        int position = 0;
        for (int i = 0; i < messageInfoList.size(); i++) {
            ZIMMessage oldMessage = messageInfoList.get(i).getZIMMessage();
            ZIMMessage newMessage = info.getZIMMessage();
            if (oldMessage.getLocalMessageID() == info.getZIMMessage().getLocalMessageID() && newMessage.getSentStatus() != oldMessage.getSentStatus()) {
                position = i;
                break;
            }
        }
        if (position!=0){
            messageInfoList.set(position,info);
            notifyItemChanged(position);
        }
    }

    public List<MessageInfo> getMessageInfoList(){
        return messageInfoList;
    }

    public void setMemberList(List<ZIMGroupMemberInfo> memberList){
        this.memberList = memberList;
        notifyDataSetChanged();

    }

    public void setDetailsPost(GetRequestWithEditPostGetDetailsModel.Data data, int postPos) {
        this.postData = data;
        notifyItemChanged(postPos);
    }

    @Override
    public boolean handleMessage(@NonNull Message msg ) {

        switch (msg.what) {
            case MSG_UPDATE_SEEK_BAR: {
                baseViewHolder.seekBar.setProgress(mediaPlayer.getCurrentPosition());
                uiUpdateHandler.sendEmptyMessageDelayed(MSG_UPDATE_SEEK_BAR, 100);
                return true;
            }
        }
        return false;
    }
}

滚动回收器后,搜索栏拇指的位置设置为如下图所示结束; [在此输入图像描述][1]

java android android-studio android-recyclerview seekbar
1个回答
0
投票

您面临的问题是因为您正在使用

seekbar
获取
messageInfoList.get(position).getSeekBarProgressValue()
的当前进度,但并未将值更新到列表中。

© www.soinside.com 2019 - 2024. All rights reserved.