안드로이드 짧은 비디오 재생을 슬라이딩 (A)


이 논문은 PagerSnapHelper와 RecyclerView의 사용이 짧은 비디오 재생 슬라이드 컨텐츠를 달성 설명합니다.

짧은 비디오 .gif 중요

1. 홈 컨텐츠 건설

홈 레이아웃 파일은 RecyclerView, 대응 어댑터 RecyclerView을 정의합니다.

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rv_little_video"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

비디오 재생 어댑터 입력 FrameLayout이 컨테이너와 커버 이미지 뷰를 추가합니다.

<FrameLayout
    android:id="@+id/fl_content_item"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black">

<ImageView
    android:id="@+id/iv_thumb_item"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop" />

</FrameLayout>

RecyclerView 슬라이드 관리를 정의합니다

PagerSnapHelper는 LinearLayoutManager의 실현 슬라이드 관리 및 모니터 작업을 결합했다.

PagerSnapHelper 소개

PagerSnapHelper는 유사한 행동을 달성 할 수 있습니다
ViewPager를. #attachToRecyclerView (RecyclerView를)}를 사용하여 RecyclerView에 PagerSnapHelper를 부착 한 후 android.view.ViewGroup.LayoutParams # MATCH_PARENT 높이와 폭을 갖도록 RecyclerView과 RecyclerView.Adapter의 항목을 모두 설정합니다.

번역 : PagerSnapHelper은 다음과 비슷한 동작 달성 할 수
ViewPager를. RecyclerView 및 RecyclerView.Adapter 항목은 높이로 설정되고, 폭 android.view.ViewGroup.LayoutParams # MATCH_PARENT 다음 PagerSnapHelper RecyclerView 추가 #attachToRecyclerView (RecyclerView)을 이용}.


사용자 정의 RecyclerView 관리자

LinearLayoutManager, 당신은 측면 슬라이드를 사용하려는 경우, 길이 방향으로 슬라이드 기본 RecyclerView 매니저는 슬라이딩 방향은 RecyclerView.HORIZONTAL 설정됩니다. 마찬가지로, 또한 슬라이딩 방향을 변경 setOrientation (RecyclerView.HORIZONTAL) 방법을 사용할 수있다.

public class PagerLayoutManager extends LinearLayoutManager implements RecyclerView.OnChildAttachStateChangeListener {

    private OnPageChangedListener mOnPageChangedListener;
    
    private PagerSnapHelper mSnapHelper;
    
    /**
     * 移动方向标记
     */
    private int direction;
    
    public PagerLayoutManager(Context context) {
        super(context);
        mSnapHelper = new PagerSnapHelper();
    }
    
    /**
     * PagerSnapHelper绑定RecyclerView,同时为监听RecyclerView子布局附着,脱离,进行滑动页面内容控制
     *
     * @param view RecyclerView
     */
    @Override
    public void onAttachedToWindow(RecyclerView view) {
        super.onAttachedToWindow(view);
        mSnapHelper.attachToRecyclerView(view);
        view.addOnChildAttachStateChangeListener(this);
    }
    
    /**
     * 滑动状态改变监听,滑动完毕后进行播放控制
     *
     * @param state 滑动状态
     */
    @Override
    public void onScrollStateChanged(int state) {
    super.onScrollStateChanged(state);
    
        if (state == RecyclerView.SCROLL_STATE_IDLE) {
            View view = mSnapHelper.findSnapView(this);
            if (view == null) {
                return;
            }
            int position = getPosition(view);
            if (mOnPageChangedListener != null && getChildCount() == 1) {
                mOnPageChangedListener.onPageSelected(position, position == getItemCount() - 1);
            }
        }
    
    }
    
    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        direction = dx;
        return super.scrollHorizontallyBy(dx, recycler, state);
    }
    
    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        direction = dy;
        return super.scrollVerticallyBy(dy, recycler, state);
    }
    
    @Override
    public void onChildViewAttachedToWindow(@NonNull View view) {
        if (mOnPageChangedListener != null && getChildCount() == 1) {
            mOnPageChangedListener.onPageInitComplete();
        }
    }
    
    @Override
    public void onChildViewDetachedFromWindow(@NonNull View view) {
        if (mOnPageChangedListener != null) {
            mOnPageChangedListener.onPageRelease(getPosition(view), direction >= 0);
        }
    }
    
    public void setOnPageChangedListener(OnPageChangedListener mOnPageChangedListener) {
        this.mOnPageChangedListener = mOnPageChangedListener;
    }
    
    public interface OnPageChangedListener {
    
        /**
         * 初始化子布局加载完成
         */
        void onPageInitComplete();
        
        /**
         * 子布局脱离
         *
         * @param position 子布局在RecyclerView位置
         * @param isNext   是否有下一个
         */
        void onPageRelease(int position, boolean isNext);
        
        /**
         * 子布局附着
         *
         * @param position 子布局在RecyclerView位置
         * @param isLast   是否最后一个
         */
        void onPageSelected(int position, boolean isLast);
    }

}

3. 슬라이드 비디오를 달성

RecyclerView 관리자 PagerLayoutManager 같이, 어댑터는 데이터 콘텐츠, 커버 디스플레이를 설정하고,이 시간은 콜백 onPageInitComplete ()에있어서, 상기 제 1 비디오 재생 될 것이다. 다음, 콜백 () 메소드를 onPageSelected 플레이어에 표시 페이지의 콘텐츠를 선택하고, RecyclerView 슬라이드, 페이지의 종료 후 슬라이드 것이다 첫번째 콜백 관리자 onPageRelease () 메소드를 들어, 당신은 정지 릴리스 플레이어에있을 수 있습니다.

슬라이드를 해제하면, 현재 위치에 해당 페이지 또는 반복 영상 정지를 방지하기 위해 수행되어야하는 결정된다.

mPagerLayoutManager = new PagerLayoutManager(this);
mPagerLayoutManager.setOnPageChangedListener(new PagerLayoutManager.OnPageChangedListener() {
@Override
public void onPageInitComplete() {
    int position = mPagerLayoutManager.findFirstVisibleItemPosition();
    if (position != -1) {
        mCurrentPosition = position;
    }
    startPlay(mCurrentPosition);
}

@Override
public void onPageRelease(int position, boolean isNext) {
    if (mCurrentPosition == position) {
        stopPlay();
    BaseViewHolder viewHolder = (BaseViewHolder) mRvLittleVideo.findViewHolderForLayoutPosition(mCurrentPosition);
    if (viewHolder != null) {
        ImageView mVideoThumb = viewHolder.getView(R.id.iv_thumb_item);
    if (mVideoThumb != null) {
        mVideoThumb.setVisibility(View.VISIBLE);
    }
    }
    }
}

@Override
public void onPageSelected(int position, boolean isLast) {
    if (mCurrentPosition == position) {
        return;
    }
    startPlay(position);
    mCurrentPosition = position;
    }
});

mRvLittleVideo.setLayoutManager(mPagerLayoutManager);

mLittleVideoAdapter = new LittleVideoAdapter();
mRvLittleVideo.setAdapter(mLittleVideoAdapter);

3. 플레이어 초기화 및 정지, 플레이

초기화 플레이어의 콘텐츠

private void initVideo() {

    mVideoView = new LittleVideoView(this);
    GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL);
    mGsySmallVideoHelperBuilder = new GSYVideoOptionBuilder();
    mGsySmallVideoHelperBuilder
            .setLooping(true)
            .setCacheWithPlay(true)
            .setIsTouchWiget(false)
            .setVideoAllCallBack(new GSYSampleCallBack() {
                @Override
                public void onPrepared(String url, Object... objects) {
                    super.onPrepared(url, objects);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            BaseViewHolder viewHolder = (BaseViewHolder) mRvLittleVideo.findViewHolderForLayoutPosition(mCurrentPosition);
                            if (viewHolder != null) {
                                ImageView mVideoThumb = viewHolder.getView(R.id.iv_thumb_item);
                                if (mVideoThumb != null) {
                                    mVideoThumb.setVisibility(View.INVISIBLE);
                                }
                            }
                        }
                    }, 100);
                }
            });
}

비디오 콘텐츠를 재생을 시작, 플레이어보기로드

private void startPlay(int position) {
    if (position < 0 || position >= mLittleVideoAdapter.getData().size()) {
        return;
    }
    BaseViewHolder holder = (BaseViewHolder) mRvLittleVideo.findViewHolderForLayoutPosition(position);
    ViewParent parent = mVideoView.getParent();
    if (parent instanceof FrameLayout) {
        ((ViewGroup) parent).removeView(mVideoView);
    }
    if (holder != null) {
        FrameLayout mVideoContent = holder.getView(R.id.fl_content_item);
        mVideoContent.addView(mVideoView, 0);
        mGsySmallVideoHelperBuilder.setUrl(mLittleVideoAdapter.getData().get(position).getUrl());
        mGsySmallVideoHelperBuilder.build(mVideoView);
        mVideoView.startPlayLogic();
    }
}

정지 재생, 제거보기

private void stopPlay() {
    mVideoView.release();
    ViewParent parent = mVideoView.getParent();
    if (parent instanceof FrameLayout) {
        ((FrameLayout) parent).removeView(mVideoView);
    }
}

3. 플레이어의 콘텐츠

예는 GSY 열린 플레이어에서 상속 된 사용자 지정 레이아웃 공간 플레이어, 비디오 플레이어 단순히 물론, 사용되는 다른 플레이어 IjkPlayer 만두 등을 사용.

public class LittleVideoView extends StandardGSYVideoPlayer {

    public LittleVideoView(Context context, Boolean fullFlag) {
        super(context, fullFlag);
    }

    public LittleVideoView(Context context) {
        super(context);
    }

    public LittleVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public int getLayoutId() {
        return R.layout.empty_control_video;
    }
}

레이아웃 파일

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black">

    <FrameLayout
    android:id="@+id/surface_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    
    </FrameLayout>

</RelativeLayout>

이 간단한 슬라이딩 플레이가 완료 예 단지 실현 방법과 모든 사람들이 참조를 배울 수있는 아이디어를 제공하고, 실제 사용은 캡슐화 할 수 있으며, 향후의 처리는 다음 플레이어는 일부 슬라이드 어댑터를 추가합니다 로드 데이터 처리와 멀티 레이아웃 콘텐츠 프리젠 테이션 등.

짧은 비디오 재생 안드로이드 슬라이드 (II)

어떤 공공 관심사는 : 더 흥미로운 기술, 도구, 가십, 자원을 확인하기 위해 몇 번 울리지 않습니다.
있는 공개 .JPG 없습니다

추천

출처www.cnblogs.com/jqnl/p/12131965.html