当前位置:网站首页>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



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
AdapterViewPager RecyclerView.Adapter
Slide monitor addPageChangeListenerregisterOnPageChangeCallback
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

 Insert picture description here

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) {
    
        }
    };

原网站

版权声明
本文为[Cheng @ Cheng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070655042690.html