android ViewPager2的使用教程

谷歌發佈了Android的ViewPager2測試版,讓咱們看看它有什麼不一樣。java

Android ViewPager2

首先使用ViewPager2,先在build.gradle添加依賴android

implementation 'androidx.viewpager2:viewpager2:1.0.0-alpha01'
複製代碼

Android ViewPager2的特性

  • 從右到左的佈局支持
  • 垂直方向
  • RecyclerView.Adapter取代PagerAdapter
  • registerOnPageChangeCallback 取代 addPageChangeListener
  • 更高效的notifyDataSetChanged

ViewPaver2與ViewPager的區別

一樣在xml中使用同樣。git

<androidx.viewpager2.widget.ViewPager2
       android:id="@+id/viewpager2"
       android:layout_width="match_parent"
       android:layout_height="match_parent"/>
複製代碼

在之前的ViewPager的addOnPageChangeListener方法,咱們須要覆蓋三個方法。回顧下代碼以下github

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
複製代碼

在ViewPager2中,再也不須要這樣的重寫。bash

mviewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
        });
複製代碼

垂直方向屬性

默認是水平方向ORIENTATION_HORIZONTAL,垂直是ORIENTATION_VERTICALapp

mviewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
複製代碼

ViewPager2與RecycleView的結合使用

接下來,咱們使用RecyclerView.Adapter來結合ViewPager2一塊兒使用。再也不須要像ViewPager使用FragmentStateAdapter。ide

項目結構以下: 佈局

struct.png

activity_main.xml代碼測試

<?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">

   <androidx.viewpager2.widget.ViewPager2
       android:id="@+id/viewpager2"
       android:layout_width="match_parent"
       android:layout_height="match_parent"/>


</androidx.constraintlayout.widget.ConstraintLayout>
複製代碼

MainActivity的代碼gradle

public class MainActivity extends AppCompatActivity {
    ViewPager2 mviewPager2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mviewPager2 = findViewById(R.id.viewpager2);
        List<String> list = new ArrayList<>();
        list.add("頁面一");
        list.add("頁面二");
        list.add("頁面三");
        list.add("頁面四");

        mviewPager2.setAdapter(new ViewPagerAdapter(this, list, mviewPager2));

    }
}
複製代碼

列表Item的佈局recycleview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="@android:color/white"
        android:textSize="32sp"
        tools:text="item" />
</RelativeLayout>

複製代碼

ViewPagerAdapter的代碼以下,使用跟RecycleView的adapter徹底同樣

package com.chaowen.androidviewpager2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

/**
 * @Author: wuchaowen
 * @Description:
 * @Time:
 **/
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewHolder> {
    private List<String> mData;
    private LayoutInflater mInflater;
    private ViewPager2 viewPager2;


    private int[] colorArray = new int[]{android.R.color.black, android.R.color.holo_blue_dark, android.R.color.holo_green_dark, android.R.color.holo_red_dark};


    public ViewPagerAdapter(Context context, List<String> data, ViewPager2 viewPager2) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
        this.viewPager2 = viewPager2;
    }

    @NonNull
    @Override
    public ViewPagerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recycleview_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewPagerAdapter.ViewHolder holder, int position) {
        String animal = mData.get(position);
        holder.myTextView.setText(animal);
        holder.relativeLayout.setBackgroundResource(colorArray[position]);

    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView myTextView;
        RelativeLayout relativeLayout;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.tvTitle);
            relativeLayout = itemView.findViewById(R.id.container);

        }
    }
}

複製代碼

運行效果

viewpager.gif

踩坑1 Androidx和Android support庫不能共存

Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
	is also present at [androidx.core:core:1.1.0-alpha04] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
	Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:6:5-22:19 to override.
複製代碼

解決方案

  • 將build tools更新到3.2.0,gradle更新到4.6,依賴庫統一更新到28.0.0,這一步很是重要,不然會致使第二步不能徹底轉換成功

  • 選擇工程右鍵→Refactor→Migrate to Androidx

    viewpager2.png

  • 選中全部須要重命名的目錄,執行Do Refactor

    viewpager2_1.png

  • 發現已經看不到support庫了,運行成功安裝app。

項目代碼下載

相關文章
相關標籤/搜索