当前位置:网站首页>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) {
}
};
边栏推荐
- Upload taro pictures to Base64
- Octopus future star won a reward of 250000 US dollars | Octopus accelerator 2022 summer entrepreneurship camp came to a successful conclusion
- 进程间的通信方式
- Jenkins modifies the system time
- H5网页播放器EasyPlayer.js如何实现直播视频实时录像?
- 在EXCEL写VBA连接ORACLE并查询数据库中的内容
- nlohmann json
- 4、 Fundamentals of machine learning
- DRF authentication, permissions, and flow restrictions (only for views in DRF)
- CMD startup software passes in parameters with spaces
猜你喜欢
Binary tree high frequency question type
Yapi test plug-in -- cross request
Strategic cooperation subquery becomes the secret weapon of Octopus web browser
Netease cloud wechat applet
Over 100000 words_ Ultra detailed SSM integration practice_ Manually implement permission management
[4G/5G/6G专题基础-147]: 6G总体愿景与潜在关键技术白皮书解读-2-6G发展的宏观驱动力
十二、排序
信息安全实验一:DES加密算法的实现
信息安全实验二 :使用X-SCANNER扫描工具
Information Security Experiment 3: the use of PGP email encryption software
随机推荐
Nested (multi-level) childrn routes, query parameters, named routes, replace attribute, props configuration of routes, params parameters of routes
Pytest installation (command line installation)
js逆向教程第二发-猿人学第一题
IIS faked death this morning, various troubleshooting, has been solved
Pick up the premise idea of programming
(3/8) method parameters of improper use of enumeration (2)
Oracle安装增强功能出错
flex弹性布局
IIS redirection redirection appears eurl axd
网易云微信小程序
Mysql database transaction learning notes
Jenkins automated email
Sublime Text4 download the view in bower and set the shortcut key
Information Security Experiment 2: using x-scanner scanning tool
JS逆向教程第一发
Pycharm create a new file and add author information
**grafana安装**
shake数据库中怎么使用Mongo-shake实现MongoDB的双向同步啊?
消费互联网的产业链其实是很短的,它仅仅承接平台上下游的对接和撮合的角色
Entity of cesium data visualization (Part 1)