Android UI界面翻页滚动 Android用viewPager2实现UI界面翻页滚动的效果
Lee坚武 人气:0想了解Android用viewPager2实现UI界面翻页滚动的效果的相关内容吗,Lee坚武在本文为您仔细讲解Android UI界面翻页滚动的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,viewPager2,Android,UI界面,Android,翻页滚动,下面大家一起来学习吧。
1.先在build.gradle(Module)下添加引用viewPager2的库
implementation 'androidx.viewpager2:viewpager2:1.0.0'
2.在MainActivity下新建一个viewPager2
ViewPager2 viewPager = findViewById(R.id.viewPager); ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(); viewPager.setAdapter(viewPagerAdapter);
xml也要导入ViewPager2
<androidx.viewpager2.widget.ViewPager2 android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/viewPager" android:background="@color/teal_200" ></androidx.viewpager2.widget.ViewPager2>
3.创建个ViewPagerAdapter
package com.zhizhu.test03; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewPagerViewHolder> { private List<String> titles = new ArrayList<>(); public ViewPagerAdapter(){ titles.add("111"); titles.add("222"); titles.add("99999"); titles.add("333"); titles.add("99888"); } @NonNull @Override public ViewPagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ViewPagerViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pager, parent, false)); } @Override public void onBindViewHolder(@NonNull ViewPagerViewHolder holder, int position) { holder.mTV.setText(titles.get(position)); } @Override public int getItemCount() { return 5; } class ViewPagerViewHolder extends RecyclerView.ViewHolder{ TextView mTV; RelativeLayout mContainer; public ViewPagerViewHolder(@NonNull View itemView) { super(itemView); mContainer = itemView.findViewById(R.id.container); mTV = itemView.findViewById(R.id.tvTitle); } } }
还要创建个item_pager.xml文件
<?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" android:id="@+id/container"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tvTitle" android:layout_centerInParent="true" android:textColor="@color/black" android:textSize="30dp" android:text="88888"></TextView> </RelativeLayout>
最终效果图:
加载全部内容