RecyclerView中的Seekbar进度发生了变化

时间:2018-01-13 21:28:43

标签: java android performance android-recyclerview seekbar

问题: 我有recyclerview和mediaplayer 我有很多搜索栏(由RecyclerView.Adapter管理),通过更改一行项的搜索栏,它会自动更改上一行或下一行的搜索栏。

主要问题是recyclerview的第二项是播放歌曲,我更改了最后一项的搜索栏,它也改变了第二项的搜索栏。

我猜两个观点都使用相同的参考。

@ViewholderClass

public class AudioViewHolder extends BaseHolder<ChatViewModelList> {
    private Context context;
    TextView tvTimestamp;
    ImageView ivUser;
    private final TextView startTime;
   static PlayAudioFragment playAudioFragment;

    private View loadingAudio;
    private ImageView playAudio;
    private TextView durationAudio;
    private SeekBar progressAudio;

    public AudioViewHolder(View itemView, Context context, PlayAudioFragment playAudioFragment) {
        super(itemView);
        this.context = context;
        tvTimestamp = (TextView) itemView.findViewById(R.id.ImgTime);
        ivUser = (ImageView) itemView.findViewById(R.id.ContactListIcon);
        this.playAudioFragment = playAudioFragment;
        loadingAudio = itemView.findViewById(R.id.chatMessageLoadingAudio);
        playAudio = (ImageView) itemView.findViewById(R.id.chatMessagePlayAudio);
        progressAudio = (SeekBar) itemView.findViewById(R.id.chatMessageProgressAudio);
        durationAudio = (TextView) itemView.findViewById(R.id.chatMessageDurationAudio);
        startTime = (TextView) itemView.findViewById(R.id.startTime);

    }

    @Override
    public void BindData(final ChatViewModelList model) {
        setIvUser(model.getMessage().getUserModel().getPhoto_profile());
        setTvTimestamp(model.getMessage().getTimeStamp());

        if (model.getMessage().getFileModel().getType().equals(Media.Type.Audio)) {
            startTime.setText(TimeFormatter.getDurationString(0));
            progressAudio.setProgress(0);
            progressAudio.setMax(100);
            playAudio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    FileModel fileModel = model.getMessage().getFileModel();
                    if (playAudioFragment.isStopped() || !playAudioFragment.getCurrentMedia().equals(fileModel)) {
                        playAudioFragment.resetPlayback();
                        playAudioFragment.setCustomPlayback(playAudio, durationAudio, loadingAudio, progressAudio);
                        playAudioFragment.loadNewMedia(fileModel);
                    } else {
                        playAudioFragment.togglePlayback();
                    }
                }
            });

            if (!model.getMessage().getFileModel().equals(playAudioFragment.getCurrentMedia())) {
                loadingAudio.setVisibility(View.GONE);
                progressAudio.setProgress(0);
                playAudio.setImageResource(R.drawable.ic_play_arrow_blue_36dp);
                int duration = (int) model.getMessage().getFileModel().getDuration();
                long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
                long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
                        - TimeUnit.MINUTES.toSeconds(minutes);
                durationAudio.setText(String.format("%02d:%02d", minutes, seconds));
                if (playAudioFragment.isPlayView(playAudio)) {
                    playAudioFragment.resetPlayback();
                }
            } else {
                playAudioFragment.setCustomPlayback(playAudio, durationAudio, loadingAudio, progressAudio);
            }

        }


    }

    public void setIvUser(String urlPhotoUser) {
        if (ivUser == null) return;
        Glide.with(ivUser.getContext()).load(urlPhotoUser).centerCrop().placeholder(R.drawable.ic_menu_camera).transform(new CircleTransform(ivUser.getContext())).override(40, 40).into(ivUser);
    }

    public void setTvTimestamp(String timestamp) {
        if (tvTimestamp == null) return;
        tvTimestamp.setText(DateUtils.convertMillisecondsToTime(Long.valueOf(timestamp)));
    }
}

用于播放音频的片段代码。

public class PlayAudioFragment extends DialogFragment {

    public static final String TAG = "RecordAudioFragment";

    public static final int MAX_DURATION_MS = 50 * 1000;

    public static final int IDLE_STATUS = 0;
    public static final int READY_STATUS = 2;
    public static final int PLAYER_STATUS = 3;

    public static final int PLAYING_STATUS = 0;
    public static final int PAUSED_STATUS = 1;
    public static final int STOPPED_STATUS = 2;

    public static final String EXTRA_MEDIA = "media";

    public TextView startTime;
    public TextView endTime;
    public ImageView play;
    public SeekBar progress;
    public TextView mainAction;
    public TextView cancel;
    public View loadingContainer;

    public Handler handler;
    public static File recordedAudio;
    public MediaRecorder mediaRecorder;
    public MediaPlayer mediaPlayer;

    public int recordingStatus = IDLE_STATUS;
    public int playbackStatus = STOPPED_STATUS;

    public int duration = 0;

    public CountDownTimer timer;

    private RelativeLayout root;
    private FileModel media;

    public static PlayAudioFragment newInstance(Media media) {
        Bundle args = new Bundle();
        args.putParcelable(EXTRA_MEDIA, media);
        PlayAudioFragment fragment = new PlayAudioFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_record_audio, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setupObjects();
        setupView(view);
        setupDataIfExists();
    }


    public void setupDataIfExists() {
        Bundle args = getArguments();
        if (args != null && args.containsKey(EXTRA_MEDIA)) {
            media = args.getParcelable(EXTRA_MEDIA);
            switchRecordingStatus(PLAYER_STATUS);
            root.setVisibility(View.VISIBLE);

        }
    }

    public void setupView(View view) {
        loadingContainer = view.findViewById(R.id.loadingContainer);
        endTime = (TextView) view.findViewById(R.id.endTime);
        endTime.setText(TimeFormatter.getDurationStringFromMillis(MAX_DURATION_MS));
        startTime = (TextView) view.findViewById(R.id.startTime);
        progress = (SeekBar) view.findViewById(R.id.progress);
        root = (RelativeLayout) view.findViewById(R.id.root);
        play = (ImageView) view.findViewById(R.id.play);
        play.setOnClickListener(onPlayClickListener);
        setCustomPlayback(play, startTime, loadingContainer, progress);
        mainAction = (TextView) view.findViewById(R.id.mainAction);
        cancel = (TextView) view.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
    }

    public void setCustomPlayback(ImageView play, TextView duration, View loadingContainer, SeekBar progress) {
        this.loadingContainer = loadingContainer;
        this.startTime = duration;
        this.startTime.setText(TimeFormatter.getDurationString(0));
        this.play = play;
        this.progress = progress;
        this.progress.setOnSeekBarChangeListener(onSeekBarChangeListener);
        setupObjects();
        if (recordingStatus == PLAYER_STATUS) {
            switchPlaybackStatus(PLAYING_STATUS);
            handler.post(playRunnable);
        }
    }

    public SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (mediaPlayer != null && fromUser) {
                mediaPlayer.seekTo(progress);
                handler.removeCallbacks(playRunnable);
                long minutes = TimeUnit.MILLISECONDS.toMinutes(mediaPlayer.getCurrentPosition());
                long seconds = TimeUnit.MILLISECONDS.toSeconds(mediaPlayer.getCurrentPosition())
                        - TimeUnit.MINUTES.toSeconds(minutes);
                startTime.setText(String.format("%02d:%02d", minutes, seconds));
                updateSeekBar();
            } else if (mediaPlayer == null && fromUser) {
                prepareMediaPlayerFromPoint(progress);
                updateSeekBar();
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            if (mediaPlayer != null) {
                // remove message Handler from updating progress bar
                handler.removeCallbacks(playRunnable);
            }
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (mediaPlayer != null) {
                handler.removeCallbacks(playRunnable);
                mediaPlayer.seekTo(seekBar.getProgress());
                long minutes = TimeUnit.MILLISECONDS.toMinutes(mediaPlayer.getCurrentPosition());
                long seconds = TimeUnit.MILLISECONDS.toSeconds(mediaPlayer.getCurrentPosition())
                        - TimeUnit.MINUTES.toSeconds(minutes);
                startTime.setText(String.format("%02d:%02d", minutes, seconds));
                updateSeekBar();
            }
        }
    };

    private void prepareMediaPlayerFromPoint(int progresss) {

        mediaPlayer = new MediaPlayer();

        try {
            Uri uri = Uri.fromFile(new File(media.getUrl_file()));

            String path = FileHelper.getPath(getActivity(), uri);
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            progress.setMax(mediaPlayer.getDuration());
            mediaPlayer.seekTo(progresss);
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {

                }
            });

        } catch (IOException e) {
        }

    }

    public void loadNewMedia(FileModel media) {
        this.media = media;
        stopCompletely();
        switchRecordingStatus(PLAYER_STATUS);
    }

    public boolean isStopped() {
        return playbackStatus == STOPPED_STATUS;
    }

    public boolean isPlayView(View play) {
        return this.play != null && this.play.equals(play);
    }

    public View.OnClickListener onPlayClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            togglePlayback();
        }
    };

    public void setupObjects() {
        handler = new Handler();

    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        stopCompletely();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(playRunnable);
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    public Runnable playRunnable = new Runnable() {
        @Override
        public void run() {
            if (mediaPlayer != null) {
                int mCurrentPosition = mediaPlayer.getCurrentPosition();
                progress.setProgress(mCurrentPosition);
                long minutes = TimeUnit.MILLISECONDS.toMinutes(mCurrentPosition);
                long seconds = TimeUnit.MILLISECONDS.toSeconds(mCurrentPosition)
                        - TimeUnit.MINUTES.toSeconds(minutes);
                startTime.setText(String.format("%02d:%02d", minutes, seconds));

                updateSeekBar();
            }

        }
    };

    private void updateSeekBar() {
        handler.postDelayed(playRunnable, 100);
    }


    public void stopCompletely() {
        handler.removeCallbacks(playRunnable);
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    public void stopp() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }


    public void switchRecordingStatus(int status) {
        if (cancel != null) cancel.setText("cancel");
        recordingStatus = status;
        switch (status) {
            case READY_STATUS:
                timer.cancel();
                play.setVisibility(View.VISIBLE);
                prepareToPlay();
                if (mainAction != null) mainAction.setText("Play");
                break;
            case PLAYER_STATUS:
                if (mainAction != null) mainAction.setVisibility(View.GONE);
                switchPlaybackStatus(PLAYING_STATUS);
                loadAudio();
        }
    }

    public void prepareToPlay() {
        switchPlaybackStatus(PAUSED_STATUS);
        progress.setProgress(0);
        progress.setMax(mediaPlayer.getDuration());
        startTime.setText(TimeFormatter.getDurationString(0));
        if (endTime != null) {
            if (mediaPlayer != null)
                endTime.setText(TimeFormatter.getDurationStringFromMillis(mediaPlayer.getDuration()));
            else
                endTime.setText(TimeFormatter.getDurationString(duration));
        }
    }

    public void switchPlaybackStatus(int status) {
        if (play == null) return;
        playbackStatus = status;
        play.setVisibility(View.VISIBLE);
        switch (status) {
            case PLAYING_STATUS:
                play.setImageResource(R.drawable.ic_media_pause);
                break;
            case PAUSED_STATUS:
                play.setImageResource(R.drawable.ic_play_arrow_blue_36dp);
                break;
            case STOPPED_STATUS:
                play.setImageResource(R.drawable.ic_play_arrow_blue_36dp);
                progress.setProgress(0);
        }
    }


    public void togglePlayback() {
        switch (playbackStatus) {
            case PLAYING_STATUS:
                mediaPlayer.pause();
                switchPlaybackStatus(PAUSED_STATUS);
                break;
            case STOPPED_STATUS:
            case PAUSED_STATUS:
                loadAudio();
                switchPlaybackStatus(PLAYING_STATUS);
        }
    }

    public void loadAudio() {
        if (mediaPlayer != null) {
            play.setImageResource(R.drawable.ic_media_pause);
            handler.removeCallbacks(playRunnable);
            mediaPlayer.start();
            updateSeekBar();

        } else {
            mediaPlayer = new MediaPlayer();
            try {
                if (recordingStatus == PLAYER_STATUS) {
                    Uri uri = Uri.fromFile(new File(media.getUrl_file()));
                    String path = FileHelper.getPath(getActivity(), uri);
                    mediaPlayer.setDataSource(path);
                } else
                    mediaPlayer.setDataSource(recordedAudio.getAbsolutePath());
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.prepareAsync();
                progress.setMax(mediaPlayer.getDuration());
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        startPlay();
                    }
                });
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if(mp.getCurrentPosition()!=0) {
                            resetPlayback();
                            switchPlaybackStatus(STOPPED_STATUS);
                            stopp();
                        }
                    }
                });


            } catch (IOException exception) {
                Log.e(TAG, "prepare() failed");
            }
        }
    }

    public void startPlay() {
        startTime.setText(TimeFormatter.getDurationString(0));
        if (endTime != null) {
            endTime.setText(TimeFormatter.getDurationStringFromMillis(mediaPlayer.getDuration()));
        }
        progress.setMax(mediaPlayer.getDuration());
        loadingContainer.setVisibility(View.GONE);
        handler.post(playRunnable);
        mediaPlayer.start();
    }


    public void resetPlayback() {
        if (handler != null) handler.removeCallbacks(playRunnable);
        switchPlaybackStatus(STOPPED_STATUS);
        play = null;
        duration = 0;
        progress = null;
        if (mediaPlayer != null) {
            startTime.setText(TimeFormatter.getDurationStringFromMillis(mediaPlayer.getDuration()));
        }
    }

    public FileModel getCurrentMedia() {
        return media;
    }
}

0 个答案:

没有答案