首页 > 解决方案 > 当我回到上一个视图 ViewPager2 时,ExoPlayer 没有播放 onViewRecycled

问题描述

我正在使用带有回收器视图适配器的 ViewPager2 并设置以下内容,如下所示

当我滑动屏幕并更改索引时,它适用于新索引但当我转到上一个索引时它不会播放任何视频为什么?有什么建议么??

RecyclerViewAdapter.java

@Override
public void onViewDetachedFromWindow(@NonNull VideoPlayerViewHolder holder) {
    super.onViewDetachedFromWindow(holder);
    holder.pausePlayer();
    holder.releasePlayer();
}

@Override
public void onViewAttachedToWindow(@NonNull VideoPlayerViewHolder holder) {
    super.onViewAttachedToWindow(holder);
    holder.startPlayer();
}

  @Override
public void onViewRecycled(@NonNull VideoPlayerViewHolder holder) {
    super.onViewRecycled(holder);
    holder.startPlayer();
}


 @Override
public void onBindViewHolder(@NonNull VideoPlayerViewHolder holder, int position) {
    holder.setExoplayer(getItem(position).getUrl());
}

ViewHolderr.java

  public void startPlayer() {
    player.setPlayWhenReady(true);
    player.getPlaybackState();
}

public void pausePlayer() {
 
    player.setPlayWhenReady(false);
    player.getPlaybackState();
}


public void setExoplayer(String url) {
    player = new SimpleExoPlayer.Builder(itemView.getContext()).build();
    player.setRepeatMode(Player.REPEAT_MODE_ONE);
    dataSourceFactory = new DefaultDataSourceFactory(itemView.getContext(),"exo-player");
    mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(url));
    player.prepare(mediaSource);
    playerView.setPlayer(player); //need to transfer
    player.seekTo(playbackPosition);
    player.addListener(this);
}

public void releasePlayer() {
    player.setPlayWhenReady(false);
    player.release();
    player.stop(true);
}

标签: androidandroid-recyclerviewandroid-adapterexoplayer2.xandroid-viewpager2

解决方案


像这样附加视图时设置 Exoplayer

@Override
public void onViewAttachedToWindow(@NonNull VideoPlayerViewHolder holder) {
    super.onViewAttachedToWindow(holder);
    holder.setExoplayer();
    holder.startPlayer();
}

推荐阅读