viewPager2 基本使用
1 增加依赖
dependencies {
implementation "androidx.viewpager2:viewpager2:1.0.0"
implementation 'androidx.recyclerview:recyclerview:1.1.0'
}
2.添加xml里面的viewPager2
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:background="#ccc"
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="200sp"/>
</LinearLayout>
3.使用
1.自定义 new ViewPagerAdapter()
2.viewPager.setAdapter
package com.example.viewpagerapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager2 viewPager = findViewById(R.id.viewpager);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
}
}
文件
ViewPagerAdapter.java
1.设置行数才能显示,2.加载xml需要注意
package com.example.viewpagerapplication;
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;
// 3 RecyclerView.Adapter(后面要跟着一个范型)
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewPagerViewHolder> {
private List<String> titles = new ArrayList<>();
public ViewPagerAdapter(){ // 初始化数据函数
titles.add("1");
titles.add("21");
titles.add("31");
titles.add("41");
titles.add("51");
titles.add("61");
titles.add("71");
titles.add("81");
titles.add("91");
titles.add("101");
}
@NonNull
@Override
public ViewPagerAdapter.ViewPagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// 2.1ViewPagerViewHolder 修改下面的内部类 (加载 ,解析xml的操作)
return new ViewPagerAdapter.ViewPagerViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pager,parent,false));
}
@Override
public void onBindViewHolder(@NonNull ViewPagerViewHolder holder, int position) {
// 2.ViewPagerViewHolder 修改下面的内部类
// 修改数据
holder.tV.setText(titles.get(position));
}
@Override // 设置10个滚动的数据个数 getItemCount
public int getItemCount() {
return 8;
}
// 1.建1个内部类
class ViewPagerViewHolder extends RecyclerView.ViewHolder {
TextView tV;
RelativeLayout relativeLayout;
public ViewPagerViewHolder(@NonNull View itemView) {
super(itemView);
relativeLayout = itemView.findViewById(R.id.container);
tV = itemView.findViewById(R.id.test1);
}
}
}