前言:
ViewPager 2 底层是用 RecycleView 实现
Recyclerview需要编写adapter,VIewPager2同样也需要
使用前需要导入依赖
implementation 'androidx.viewpager2:viewpager2:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
Demo1 最简单的水平翻页(垂直也可以)
1.像使用RecyclerView一样写一个adapter,完全一样,直接附上代码,不会写的可以先去简单学习以下Recyclerview
package com.example.viewpager2test.HorziontalTest;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.viewpager2test.R;
import java.util.List;
public class HorizontalVpAdapter extends RecyclerView.Adapter<HorizontalVpAdapter.ViewHolder> {
List<Integer> backColorList;
public HorizontalVpAdapter() {
}
public HorizontalVpAdapter(List<Integer> backColorList) {
this.backColorList = backColorList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
int backColor = backColorList.get(position);
holder.itemImage.setImageResource(backColor);
}
@Override
public int getItemCount() {
if (backColorList == null) {
return 0;
} else {
return backColorList.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
ViewGroup itemLayout;
ImageView itemImage;
public ViewHolder(@NonNull View itemView) {
super(itemView);
itemImage = itemView.findViewById(R.id.item_image);
}
}
}
2.在xml中放上viewPager2控件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/my_view_pager2"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.viewpager2.widget.ViewPager2>
</LinearLayout>
3.在Activity中初始化
package com.example.viewpager2test.HorziontalTest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.example.viewpager2test.R;
import java.util.ArrayList;
import java.util.List;
public class HorizontalTestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
ViewPager2 viewPager2 = this.findViewById(R.id.my_view_pager2);
HorizontalVpAdapter horizontalVpAdapter = new HorizontalVpAdapter(initData());
viewPager2.setAdapter(horizontalVpAdapter);
}
private List<Integer> initData() {
List<Integer> backgrounds = new ArrayList<>();
backgrounds = new ArrayList<>();
backgrounds.add(android.R.color.holo_blue_bright);
backgrounds.add(android.R.color.holo_red_dark);
backgrounds.add(android.R.color.holo_green_dark);
backgrounds.add(android.R.color.holo_orange_light);
backgrounds.add(android.R.color.holo_purple);
return backgrounds;
}
}
打完收工,看看效果
4.需要垂直翻页的只用加一句代码
public class HorizontalTestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
ViewPager2 viewPager2 = this.findViewById(R.id.my_view_pager2);
HorizontalVpAdapter horizontalVpAdapter = new HorizontalVpAdapter(initData());
viewPager2.setAdapter(horizontalVpAdapter);
//就加下面这一句就ok了,非常轻松
viewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
}
private List<Integer> initData() {
List<Integer> backgrounds = new ArrayList<>();
backgrounds = new ArrayList<>();
backgrounds.add(android.R.color.holo_blue_bright);
backgrounds.add(android.R.color.holo_red_dark);
backgrounds.add(android.R.color.holo_green_dark);
backgrounds.add(android.R.color.holo_orange_light);
backgrounds.add(android.R.color.holo_purple);
return backgrounds;
}
}
Demo2 带Tab的翻页
1.先写布局xml,要放上tabLayout和ViewPager2
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tablayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewpager2"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tablayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
2.用fragement
package com.example.viewpager2test.TabLayoutTest;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.viewpager2test.R;
import java.util.ArrayList;
import java.util.List;
public class PageFragment extends Fragment {
private static final String COLORS = "colors";
private static final String POSITION = "position";
private List<Integer> mColors;
private int mPosition;
public static PageFragment newsInstance(List<Integer> colors, int position) {
Bundle args = new Bundle();
args.putSerializable(COLORS, (ArrayList<Integer>) colors);
args.putInt(POSITION, position);
PageFragment pageFragment = new PageFragment();
pageFragment.setArguments(args);
return pageFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments()!=null){
mColors=(List<Integer>)getArguments().getSerializable(COLORS);
mPosition=this.getArguments().getInt(POSITION);
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.item_page, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RelativeLayout relativeLayout = view.findViewById(R.id.item_page_container);
TextView textView = view.findViewById(R.id.item_page_tv);
relativeLayout.setBackgroundResource(mColors.get(mPosition));
textView.setText("Item"+mPosition);
}
}
3.初始化
package com.example.viewpager2test.TabLayoutTest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import android.view.Menu;
import com.example.viewpager2test.R;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
public class TabLayoutTestActivity extends AppCompatActivity {
private ViewPager2 mViewPager2;
private TabLayout mTabLayout;
private List<Integer> colors = new ArrayList<>();
private ViewPagerFragmentStateAdapter mViewPagerFragmentStateAdapter;
{
colors.add(android.R.color.black);
colors.add(android.R.color.holo_purple);
colors.add(android.R.color.holo_blue_dark);
colors.add(android.R.color.holo_green_light);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_layout_test);
mTabLayout = findViewById(R.id.tablayout);
mViewPager2 = findViewById(R.id.viewpager2);
mViewPagerFragmentStateAdapter = new ViewPagerFragmentStateAdapter(this);
mViewPager2.setAdapter(mViewPagerFragmentStateAdapter);
mTabLayout.addTab(mTabLayout.newTab().setText("Tab0"));
mTabLayout.addTab(mTabLayout.newTab().setText("Tab1"));
mTabLayout.addTab(mTabLayout.newTab().setText("Tab2"));
mTabLayout.addTab(mTabLayout.newTab().setText("Tab3"));
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager2.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mViewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
mTabLayout.setScrollPosition(position, 0, false);
}
});
}
class ViewPagerFragmentStateAdapter extends FragmentStateAdapter {
public ViewPagerFragmentStateAdapter(@NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
if (colors == null) {
colors = new ArrayList<>();
}
}
@Override
public int getItemCount() {
return colors.size();
}
@NonNull
@Override
public Fragment createFragment(int position) {
return PageFragment.newsInstance(colors, position);
}
}
}
4.在不同的tab放不同的fragment
比如我想在第二页放一个其他的fragment
class ViewPagerFragmentStateAdapter extends FragmentStateAdapter {
public ViewPagerFragmentStateAdapter(@NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
if (colors == null) {
colors = new ArrayList<>();
}
}
@Override
public int getItemCount() {
//控制viewPager2的页数
return colors.size();
}
@NonNull
@Override
public Fragment createFragment(int position) {
//在这里控制你想在第几页放什么fragment
if(position==1){
return new NewPageFragment();
}
return PageFragment.newsInstance(colors, position);
}
}
Demo3 底部RadioGroup的ViewPager2
1.编写RadioTestActivity
package com.example.viewpager2test.RadioGroupTest;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.example.viewpager2test.ForceOffline__Notification.BaseActivity;
import com.example.viewpager2test.R;
import com.example.viewpager2test.TabLayoutTest.NewPageFragment;
import java.util.ArrayList;
import java.util.List;
public class RadioTestActivity extends BaseActivity {
private RadioGroup mRadioGroup;
private ViewPager2 mViewPager2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radio_test_layout);
mRadioGroup = this.findViewById(R.id.rg_vp);
mViewPager2 = this.findViewById(R.id.vp_rg);
RgAdapter rgAdapter = new RgAdapter(this);
rgAdapter.setFragmentList(initData());
mViewPager2.setAdapter(rgAdapter);
//RadioGroup中的Radio check状态变化时的回调
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_home:
mViewPager2.setCurrentItem(0);
break;
case R.id.rb_msg:
mViewPager2.setCurrentItem(1);
break;
case R.id.rg_my:
mViewPager2.setCurrentItem(2);
break;
}
}
});
//ViewPager2的当前页码变化时的回调
mViewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
int childCount = mRadioGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
RadioButton radioButton = (RadioButton) mRadioGroup.getChildAt(i);
if (i == position) {
radioButton.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
}else{
radioButton.setTextColor(getResources().getColor(R.color.colorAccent));
}
}
}
});
}
// 不同的页显示不同的fragment,丰富viewPager2的内容
private List<Fragment> initData() {
List<Fragment> list = new ArrayList<>();
list.add(NewPageFragment.getInstance());
list.add(New2PageFragment.getInstance());
list.add(New3PageFragment.getInstance());
return list;
}
}
2.编写ViewPager2的Adapter
package com.example.viewpager2test.RadioGroupTest;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
import java.util.List;
public class RgAdapter extends FragmentStateAdapter {
private List<Fragment> fragmentList;
public RgAdapter(@NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
if (fragmentList == null) {
fragmentList = new ArrayList<>();
}
}
public List<Fragment> getFragmentList() {
return fragmentList;
}
public void setFragmentList(List<Fragment> fragmentList) {
this.fragmentList = fragmentList;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return (Fragment) fragmentList.get(position);
}
@Override
public int getItemCount() {
return fragmentList.size();
}
}