当前位置:网站首页>The difference between viewpager2 and viewpager and the implementation of viewpager2 in the rotation chart
The difference between viewpager2 and viewpager and the implementation of viewpager2 in the rotation chart
2022-07-07 09:35:00 【Cheng @ Cheng】
List of articles
Preface :
2019 first Google Released ViewPager2 preview , And in the same year I/O Launch the official version on . As long as you have Suppor Library switch to AndroidX, You can use ViewPager2 Completely replace the old ViewPager.
ViewPager2 The most remarkable feature is based on RecyclerView Realization ,RecyclerView Is currently the Android The most mature end AdapterView Solution , This brings many benefits :
1、 Abandon the traditional PagerAdapter, Unified Adapter Of API/
2、 adopt LinearLayoutManager Tiktok can be achieved by longitudinal sliding.
3、 Support DiffUitl, Can pass diff Local refresh
4、 Support RTL(right-to-left) Layout , For those who need to go to sea APP Very useful
5、 Support ItemDecorator
One 、ViewPager2 and ViewPager Comparison of :
1、ViewPager2 The internal implementation is RecyclerView, therefore ViewPager2 Better performance .
2、ViewPager2 Vertical sliding can be realized ,ViewPager Only slide laterally .
3、ViewPager2 only one adapter,FragmentStateAdapter Inherited from RecyclerView.Adapter.
and ViewPager There are two adapter,FragmentStatePagerAdapter and FragmentPagerAdapter, Are inherited PagerAdapter.FragmentStatePagerAdapter and FragmentPagerAdapter The difference between the two FragmentStatePagerAdapter Can't cache ,FragmentPagerAdapter Can be cached .
4、ViewPager2 Pattern implements lazy loading , Preloading is not performed by default . Inside is through Lifecycle Yes Fragment Life cycle management .ViewPager Preloading occurs , Lazy loading needs to be implemented by ourselves .
ViewPager | ViewPager2 | |
---|---|---|
Adapter | ViewPager | RecyclerView.Adapter |
Slide monitor | addPageChangeListener | registerOnPageChangeCallback |
nothing | From right to left (RTL) The layout supports | |
nothing | Vertical support | |
nothing | Disable the function entered by the user (setUserInputEnabled、isUserInputEnabled) |
Two 、ViewPager2 Use ( Implement the carousel )
1、 Realization effect
2、 Implementation code
a、XML Layout
<RelativeLayout android:layout_width="match_parent" android:layout_height="200dp">
<!-- Shuffling figure -->
<androidx.viewpager2.widget.ViewPager2 android:id="@+id/homeFragment_view_banner" android:layout_width="match_parent" android:layout_height="200dp" android:orientation="horizontal" />
<!-- Down punctuation -->
<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、 Adapter
Adapter layout
<?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>
Adapter code
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、 complete Activity Code
Use Handler And thread to achieve the rotation function , Use LinearLayout Add points dynamically .
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;
}
/* When the app wakes up , Let the rotation chart begin to rotate */
@Override
public void onResume() {
super.onResume();
handler.postDelayed(runnable,5000);
}
/* When the application is paused , Stop the rotation of the rotation map */
@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();
// Register the rolling event listener of the rotation chart
view_banner.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
// Rotation time , Change the indication point
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);
}
}
}
});
}
// Initialize the indicator point
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);
// Add spacing to the indicated points
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() {
// Click the click effect to switch functions
@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); // Add the indicator point to the container
}
}
private final Runnable runnable = new Runnable() {
@Override
public void run() {
int currentPosition = view_banner.getCurrentItem(); // Get the current location of the rotation map
currentPosition++;
if(currentPosition==imgUrl.size()){
// restart
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) {
}
};
边栏推荐
猜你喜欢
Regular matching starts with XXX and ends with XXX
Kubernetes cluster capacity expansion to add node nodes
Pycharm importing third-party libraries
js逆向教程第二发-猿人学第一题
Oracle installation enhancements error
答案在哪里?action config/Interceptor/class/servlet
Postman setting environment variables
Impression notes finally support the default markdown preview mode
Network request process
[4G/5G/6G专题基础-147]: 6G总体愿景与潜在关键技术白皮书解读-2-6G发展的宏观驱动力
随机推荐
SAP MM STO单据的外向交货单创建后新加ITEM?
[bw16 application] Anxin can realize mqtt communication with bw16 module / development board at instruction
Unity shader (learn more about vertex fragment shaders)
Yapi test plug-in -- cross request
Jenkins+ant+jmeter use
数据库多表关联查询问题
Netease cloud wechat applet
What is MD5
如何成为一名高级数字 IC 设计工程师(5-3)理论篇:ULP 低功耗设计技术精讲(下)
【云原生】DevOps(一):DevOps介绍及Code工具使用
Postman interface debugging method
超十万字_超详细SSM整合实践_手动实现权限管理
iNFTnews | 时尚品牌将以什么方式进入元宇宙?
stm32和电机开发(从单机版到网络化)
创建一个长度为6的int型数组,要求数组元素的值都在1-30之间,且是随机赋值。同时,要求元素的值各不相同。
[SVN] what is SVN? How do you use it?
战略合作|SubQuery 成为章鱼网络浏览器的秘密武器
Some pit avoidance guidelines for using Huawei ECS
Sublime Text4 download the view in bower and set the shortcut key
Unity shader (basic concept)