Fragment中使用ViewPager滑动浏览页面

在开发中有时会遇到需要在fragment使用viewPager滑动,使用tablayout + viewPager也好,RecyclerView + ViewPager也好,达到目的就行。

我这里使用的是RecyclerView + ViewPager,达到在fragment中滑动浏览页面新闻,开撸

newFragment布局

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
    </data>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff"
        android:orientation="vertical">
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/fragHomeTab"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            android:layout_width="match_parent"
            android:layout_height="40dp" />
        <androidx.viewpager.widget.ViewPager
            android:id="@+id/homeNewViewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
</layout>

准备CenterLayoutManager,这是RecyclerView在点击item时会滑动到中心位置

public class CenterLayoutManager extends LinearLayoutManager {

    static int lastPosition = 0;
    static int targetPosition = 0;

    public CenterLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        CenterSmoothScroller smoothScroller = new CenterSmoothScroller(recyclerView.getContext());
        smoothScroller.setTargetPosition(position);
        startSmoothScroll(smoothScroller);
    }

    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int lastPosition, int position) {
        CenterLayoutManager.lastPosition = lastPosition;
        CenterLayoutManager.targetPosition = position;
        smoothScrollToPosition(recyclerView, state, position);
    }

    public static class CenterSmoothScroller extends LinearSmoothScroller {
        private static float duration = 200f;

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

        @Override
        public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
            return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
        }

        @Override
        protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
            float newDuration = duration / (Math.abs(targetPosition - lastPosition));
            return newDuration / displayMetrics.densityDpi;
        }

        @Override
        protected int calculateTimeForScrolling(int dx) {
            return super.calculateTimeForScrolling(dx);
        }
    }
}

WrapLinearLayoutManager,这个具体是RecyclerView 界面在展示的时候出现下标越界的问题,但具体真的没什么用,RecyclerView出现下标越界的问题时主要是list.clear()后直接list.addAll,暂时找到的解决方法是list.clear之后也需要adapternotifyDataSetChanged

public class WrapLinearLayoutManager extends LinearLayoutManager {
    public WrapLinearLayoutManager(Context context) {
        super(context);
    }

    public WrapLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public WrapLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
            super.onLayoutChildren(recycler, state);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }
    }
}

再准备一个继承View的类,作为添加到viewPager中的内容

public class HomeNewPagerDataView extends LinearLayout {

    private Context context;
    private LayoutInflater inflater;
    private View view;

    private RecyclerView homePagerRecView;
    private List<Object> homeListData;
    private HomeFragmentNewAdapter homeListAdapter;

    private String uId, code;

    public HomeNewPagerDataView(Context context) {
        super(context);
        this.context = context;
        inflater = LayoutInflater.from(context);
        init();
    }

    private void init(){
        view = inflater.inflate(R.layout.item_home_new_pager, this);
        homeListData = new ArrayList<>();
        homePagerRecView.setLayoutManager(new WrapLinearLayoutManager(context, RecyclerView.VERTICAL, false));
        homeListAdapter = new HomeFragmentNewAdapter(context, homeListData);
        homePagerRecView.setAdapter(homeListAdapter);
    }

    public void getData(){
        homeListData.add(new HomeNewTitleTestBean());
        homeListAdapter.notifyDataSetChanged();
    }
    //动态设置一些数据
    public void setLinkData(String uId, String code){
        this.uId = uId;
        this.code = code;
    }

}

写HomeNewPagerAdapter

public class HomeNewPagerAdapter extends androidx.viewpager.widget.PagerAdapter {

    private List<View> viewList;

    public HomeNewPagerAdapter(List<View> viewList) {
        this.viewList = viewList;
    }

    @Override
    public int getCount() {
        return viewList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override  //从当前container中删除指定位置(position)的View;
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(viewList.get(position));
    }

    @NonNull
    @Override  //第一:将当前视图添加到container中,第二:返回当前View
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        container.addView(viewList.get(position));
        return viewList.get(position);
    }

}

newFragment页面代码,关于Base可以参考以前写的,毕竟使用dataBinding真的很方便

public class HomeFragmentNew extends BaseDataBindingFragment<FragmentHomeNewBinding, HomeFragmentPresenter> {

    private List<Object> listBeans;
    private HomeClassifyListAdapter classifyListAdapter;
    private CenterLayoutManager manager;
    private int indexPosition = 0;

    private List<View> viewList;
    private HomeNewPagerAdapter pagerAdapter;
    private HomeNewPagerDataView pagerDataView;

    @Override
    protected HomeFragmentPresenter createPresenter() {
        return new HomeFragmentPresenter(this);
    }

    @Override
    protected int getContentView() {
        return R.layout.fragment_home_new;
    }

    @Override
    protected void initView() {
        manager = new CenterLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        binding.fragHomeTab.setLayoutManager(manager);
    }

    @Override
    protected void initData() {
        listBeans = new ArrayList<>();
        classifyListAdapter = new HomeClassifyListAdapter(context, listBeans);
        binding.fragHomeTab.setAdapter(classifyListAdapter);
        presenter.getHomeClassList();

        viewList = new ArrayList<>();
        pagerAdapter = new HomeNewPagerAdapter(viewList);
        binding.homeNewViewPager.setAdapter(pagerAdapter);

    }

    @Override
    protected void initListener() {
        classifyListAdapter.setListener((o, position) -> {
            binding.homeNewViewPager.setCurrentItem(position);
            //注意,这里要先跳转viewPager,再对rec进行刷新,否则会有卡顿感
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    getActivity().runOnUiThread(() -> {
                        setTabPagerView(position);
                    });
                }
            }, 300);
        });

        binding.homeNewViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

            @Override
            public void onPageSelected(int position) {
                setTabPagerView(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) { }
        });
    }

    private void setTabPagerView(int position) {
        manager.smoothScrollToPosition(
                binding.fragHomeTab,
                new RecyclerView.State(),
                indexPosition,
                position);
        if (indexPosition != position) {
            indexPosition = position;
        }
        classifyListAdapter.setSelectedPosition(position);

        pagerDataView = (HomeNewPagerDataView) viewList.get(position);
        pagerDataView.getData();
    }

}

基本撸完,在使用中学习,并记录下来,大家一起进步

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值