当前位置:网站首页>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) {
}
};
边栏推荐
- golang select机制和超时问题怎么解决
- Unity shader (pass user data to shader)
- flinkcdc 用sqlclient可以指定mysqlbinlog id执行任务吗
- 答案在哪里?action config/Interceptor/class/servlet
- sqlplus乱码问题,求解答
- Regular matching starts with XXX and ends with XXX
- Install pyqt5 and Matplotlib module
- IIS faked death this morning, various troubleshooting, has been solved
- 消费互联网的产业链其实是很短的,它仅仅承接平台上下游的对接和撮合的角色
- Pick up the premise idea of programming
猜你喜欢
Lesson 1: finding the minimum of a matrix
[4G/5G/6G专题基础-146]: 6G总体愿景与潜在关键技术白皮书解读-1-总体愿景
网易云微信小程序
JWT certification used in DRF
Postman data driven
Install pyqt5 and Matplotlib module
Information Security Experiment 4: implementation of IP packet monitoring program
华为HCIP-DATACOM-Core_03day
信息安全实验四:Ip包监视程序实现
第一讲:包含min函数的栈
随机推荐
Idea development environment installation
Mysql database transaction learning notes
沙龙预告|GameFi 领域的瓶颈和解决方案
Postman interface debugging method
Variable parameter of variable length function
golang select机制和超时问题怎么解决
Information Security Experiment 1: implementation of DES encryption algorithm
Unity uses mesh to realize real-time point cloud (I)
华为HCIP-DATACOM-Core_03day
超十万字_超详细SSM整合实践_手动实现权限管理
VSCode+mingw64
nlohmann json
Interface test API case, data and interface separation
Sublime Text4 download the view in bower and set the shortcut key
Mysql database lock learning notes
信息安全实验三 :PGP邮件加密软件的使用
Where is the answer? action config/Interceptor/class/servlet
Final keyword
Upload taro pictures to Base64
JMeter JDBC batch references data as input parameters (the simplest method for the whole website)