当前位置:网站首页>Fragment中使用ViewPager滑动浏览页面
Fragment中使用ViewPager滑动浏览页面
2022-07-28 18:46:00 【LW帝国余辉】
在开发中有时会遇到需要在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();
}
}
基本撸完,在使用中学习,并记录下来,大家一起进步
边栏推荐
- Teach you how to draw a map with ArcGIS [thermal map]
- Soft raid
- 算法面试高频题解指南【一】
- 十七年运维老兵万字长文讲透优维低代码~
- The engineering practice of super large model was polished, and Baidu AI Cloud released the cloud native AI 2.0 solution
- GIS数据漫谈(六)— 投影坐标系统
- Redis入门二:redhat 6.5安装使用
- UE4 3dui widget translucent rendering blur and ghosting problems
- 太空游戏第12课: 盾牌
- h5微信射击小游戏源码
猜你喜欢
![Teach you how to draw a map with ArcGIS [thermal map]](/img/16/993da4678667884a98e1d82db37d69.png)
Teach you how to draw a map with ArcGIS [thermal map]

Talking about canvas and three rendering modes in unity

太空射击第11课: Sound and Music

Beautiful blue background form input box style

太空射击第13课: 爆炸效果

JS drag and drop alert pop-up plug-in

Read the recent trends of okaleido tiger and tap the value and potential behind it

如何用Redis实现事物以及锁?
![[C语言刷题篇]链表运用讲解](/img/44/1de4e3f0712780680fbdc904dfe39a.png)
[C语言刷题篇]链表运用讲解

Use of DDR3 (axi4) in Xilinx vivado (4) incentive design
随机推荐
Unity package project to vs deploy hololens process summary
How to use redis to realize things and locks?
Voice controlled robot based on ROS (II): implementation of upper computer
flask 静态文件服务搭建
Explain the life cycle function in unity in detail
How can enterprises successfully complete cloud migration?
Unity performance optimization scheme arrangement
阿里云 MSE 支持 Go 语言流量防护
Raspberry pie 4B deploy yolov5 Lite using ncnn
Mysql报错:Specified key was too long; max key length is 767 bytes
[complete collection of common ADB commands and their usage (from a comprehensive summary of [wake up on Sunday)]
C reads the data in the CSV file and displays it after importing the DataTable
Pl515 SOT23-5 single / Dual Port USB charging protocol port controller Parkson electronic agent
使用ORDER BY 排序
太空射击第11课: Sound and Music
JS drag and drop alert pop-up plug-in
Learn about the native application management platform of rainbow cloud
研发效能的思考总结
Unity performance optimization
How to make the design of governance structure more flexible when the homogenization token is combined with NFT?