当前位置:网站首页>ViewPager2和VIewPager的区别以及ViewPager2实现轮播图
ViewPager2和VIewPager的区别以及ViewPager2实现轮播图
2022-07-07 06:55:00 【程@@程】
前言:
2019初Google发布了ViewPager2预览版,并在同年I/O上推出正式版。只要你已经从Suppor库切换到AndroidX,便可以使用ViewPager2完全取代旧的ViewPager。
ViewPager2最显著的特点是基于RecyclerView实现,RecyclerView是目前Android端最成熟的AdapterView解决方案,这带来诸多好处:
1、抛弃传统的PagerAdapter,统一了Adapter的API/
2、通过LinearLayoutManager可以实现类似抖音的纵向滑动
3、支持DiffUitl,可以通过diff实现局部刷新
4、支持RTL(right-to-left)布局,对于一些有出海需求的APP非常有用
5、支持ItemDecorator
一、ViewPager2和ViewPager的对比:
1、ViewPager2内部实现是RecyclerView,所以ViewPager2的性能更高。
2、ViewPager2可以实现竖向滑动,ViewPager只能横向滑动。
3、ViewPager2只有一个adapter,FragmentStateAdapter继承自RecyclerView.Adapter。
而ViewPager有两个adapter,FragmentStatePagerAdapter和FragmentPagerAdapter,均是继承PagerAdapter。FragmentStatePagerAdapter和FragmentPagerAdapter两者的区别是FragmentStatePagerAdapter不可以缓存,FragmentPagerAdapter可以缓存。
4、ViewPager2模式实现了懒加载,默认不进行预加载。内部是通过Lifecycle 对 Fragment 的生命周期进行管理。ViewPager会进行预加载,懒加载需要我们自己去实现。
ViewPager | ViewPager2 | |
---|---|---|
Adapter | ViewPager | RecyclerView.Adapter |
滑动监听 | addPageChangeListener | registerOnPageChangeCallback |
无 | 从右到左 (RTL) 的布局支持 | |
无 | 垂直方向支持 | |
无 | 停用用户输入的功能(setUserInputEnabled、isUserInputEnabled) |
二、ViewPager2的使用(实现轮播图)
1、实现效果
2、实现代码
a、XML布局
<RelativeLayout android:layout_width="match_parent" android:layout_height="200dp">
<!--轮播图-->
<androidx.viewpager2.widget.ViewPager2 android:id="@+id/homeFragment_view_banner" android:layout_width="match_parent" android:layout_height="200dp" android:orientation="horizontal" />
<!--下标点-->
<LinearLayout android:id="@+id/homeFragment_view_dot" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="5dp"/>
</RelativeLayout>
b、适配器
适配器布局
<?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" >
<ImageView android:id="@+id/itemBanner_iv_img" android:layout_width="match_parent" android:layout_height="200dp" android:scaleType="fitXY"/>
</RelativeLayout>
适配器代码
public class BannerAdapter extends RecyclerView.Adapter<BannerAdapter.ViewHolder> {
private Context context;
private List<Integer> imgUrl;
public BannerAdapter(Context context,List<Integer> imgUrl){
this.context = context;
this.imgUrl = imgUrl;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout_banner,parent,false));
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Glide.with(context).load(imgUrl.get(position)).into(holder.iv_img);
}
@Override
public int getItemCount() {
return imgUrl.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
ImageView iv_img;
public ViewHolder(View itemView) {
super(itemView);
iv_img = itemView.findViewById(R.id.itemBanner_iv_img);
}
}
}
c、完整Activity代码
使用Handler和线程实现轮播功能,使用LinearLayout动态添加点。
private ViewPager2 view_banner;
private LinearLayout layout_dot;
private List<Integer> imgUrl;
private List<ImageView> dotList;
private BannerAdapter bannerAdapter;
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
initViews(view);
return view;
}
/* 当应用被唤醒时,让轮播图开始轮播 */
@Override
public void onResume() {
super.onResume();
handler.postDelayed(runnable,5000);
}
/* 当应用被暂停时,让轮播图停止轮播 */
@Override
public void onPause() {
super.onPause();
handler.removeCallbacks(runnable);
}
private void initViews(View view) {
view_banner = view.findViewById(R.id.homeFragment_view_banner);
layout_dot= view.findViewById(R.id.homeFragment_view_dot);
imgUrl = new ArrayList<>();
dotList = new ArrayList<>();
imgUrl.add(R.mipmap.aa);
imgUrl.add(R.mipmap.ab);
bannerAdapter = new BannerAdapter(context,imgUrl);
view_banner.setAdapter(bannerAdapter);
initIndicatorDots();
//注册轮播图的滚动事件监听器
view_banner.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
//轮播时,改变指示点
super.onPageSelected(position);
for(int i = 0; i < dotList.size(); i++){
if(i==position){
dotList.get(i).setBackgroundResource(R.drawable.shape_dot_blue);
}else{
dotList.get(i).setBackgroundResource(R.drawable.shape_dot_gray);
}
}
}
});
}
//初始化指示点
private void initIndicatorDots(){
for(int i = 0; i < imgUrl.size(); i++){
ImageView imageView = new ImageView(context);
if (i == 0) imageView.setBackgroundResource(R.drawable.shape_dot_blue);
else imageView.setBackgroundResource(R.drawable.shape_dot_gray);
//为指示点添加间距
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0,0,10,0);
imageView.setLayoutParams(layoutParams);
int index = i;
imageView.setOnClickListener(new View.OnClickListener() {
//点击点击效果进行切换功能
@Override
public void onClick(View v) {
view_banner.setCurrentItem(index);
for(ImageView iv :dotList){
iv.setBackgroundResource(R.drawable.shape_dot_gray);
}
v.setBackgroundResource(R.drawable.shape_dot_blue);
}
});
dotList.add(imageView);
layout_dot.addView(imageView); //将指示点添加进容器
}
}
private final Runnable runnable = new Runnable() {
@Override
public void run() {
int currentPosition = view_banner.getCurrentItem(); //获得轮播图当前的位置
currentPosition++;
if(currentPosition==imgUrl.size()){
//重新开始
view_banner.setCurrentItem(0,true);
}else{
view_banner.setCurrentItem(currentPosition,true);
}
handler.postDelayed(runnable,5000);
}
};
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
}
};
边栏推荐
- Difference between process and thread
- How to speed up video playback in browser
- Netease cloud wechat applet
- Integer or int? How to select data types for entity classes in ORM
- Binary tree high frequency question type
- Jenkins modifies the system time
- Skill review of test engineer before interview
- MySQL common statements
- 第一讲:寻找矩阵的极小值
- Jenkins task grouping
猜你喜欢
MongoDB怎么实现创建删除数据库、创建删除表、数据增删改查
華為HCIP-DATACOM-Core_03day
如何使用clipboard.js库实现复制剪切功能
flex弹性布局
STM32 and motor development (from stand-alone version to Networking)
C language pointer (exercises)
Jenkins+ant+jmeter use
Skill review of test engineer before interview
Information Security Experiment 4: implementation of IP packet monitoring program
[cloud native] Devops (I): introduction to Devops and use of code tool
随机推荐
Kubernetes cluster capacity expansion to add node nodes
Jmeters use
stm32和电机开发(从单机版到网络化)
Nested (multi-level) childrn routes, query parameters, named routes, replace attribute, props configuration of routes, params parameters of routes
十二、排序
asp. How to call vb DLL function in net project
在EXCEL写VBA连接ORACLE并查询数据库中的内容
Dynamics 365online applicationuser creation method change
Postman setting environment variables
JS inheritance prototype
Using JWT to realize login function
Pytest+request+allure+excel interface automatic construction from 0 to 1 [familiar with framework structure]
Dynamics 365Online ApplicationUser创建方式变更
【云原生】DevOps(一):DevOps介绍及Code工具使用
Unity3d interface is embedded in WPF interface (mouse and keyboard can respond normally)
4、 Fundamentals of machine learning
sqlplus乱码问题,求解答
IIS redirection redirection appears eurl axd
Jenkins automated email
Unity shader (learn more about vertex fragment shaders)