Android ViewPager2 可垂直左右滑动使用【java】

ViewPager2位于androidx包下,也就是它不像ViewPager一样被内置在系统源码中。因此,使用ViewPager2需要额外的添加依赖库。另外,android support中不包含ViewPager,也就是要使用ViewPager2必须迁移到androidx才可以。

添加依赖

dependencies {
    implementation "androidx.viewpager2:viewpager2:1.0.0"
}

布局:

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

        android:layout_width="match_parent"
        android:layout_height="280dp"
        app:layout_constraintBottom_toTopOf="@+id/btn"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="切换"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>

适配器:

package com.loaderman.viewpage2;


import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

import java.util.ArrayList;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<PagerViewHolder> {
    List<String> list= new ArrayList<>();
    String[] colors = {"#FF00CC","#41F1E5","#8D41F1","#FF99CC"};
    public MyAdapter() {
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
    }

    @NonNull
    @Override
    public PagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_page, parent, false);
        return new PagerViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull PagerViewHolder holder, int position) {
        holder.tv.setText(list.get(position));
        holder.tv.setBackgroundColor(Color.parseColor(colors[position]));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}
class PagerViewHolder extends RecyclerView.ViewHolder{

    public TextView tv;
    public PagerViewHolder(@NonNull View itemView) {
        super(itemView);
        tv=itemView.findViewById(R.id.tv_text);
    }
}

item_page.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:id="@+id/tv_text"
        android:background="@color/colorPrimaryDark"
        android:layout_width="match_parent"
        android:layout_height="280dp"
        android:gravity="center"
        android:textColor="#ffffff"
        android:textSize="22sp" />
</LinearLayout>

FragmentStateAdapter

package com.loaderman.viewpage2;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;



public class MyFragmentStateAdapter extends FragmentStateAdapter{


    public MyFragmentStateAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return FragmentFactory.getFragment(position);
    }

    @Override
    public int getItemCount() {
        return 4;
    }
}

页面缩放

package com.loaderman.viewpage2;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.viewpager2.widget.ViewPager2;
//页面缩放
public class ScaleInTransformer implements ViewPager2.PageTransformer {
    final float DEFAULT_MIN_SCALE = 0.85f;
    final float DEFAULT_CENTER = 0.5f;
    final float mMinScale = DEFAULT_MIN_SCALE;
    @Override
    public void transformPage(@NonNull View view, float position) {
        view.setElevation(-Math.abs(position));
        float pageWidth = view.getWidth();
        float pageHeight = view.getHeight();

        view.setPivotY((pageHeight / 2));
        view.setPivotX ((pageWidth / 2));
        if (position < -1) {
            view.setScaleX(mMinScale);
            view.setScaleY(mMinScale);
            view.setPivotX(pageWidth);
        } else if (position <= 1) {
            if (position < 0) {
                float scaleFactor = (1 + position) * (1 - mMinScale) + mMinScale;
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);
                view.setPivotX(pageWidth * (DEFAULT_CENTER + DEFAULT_CENTER * -position));

            } else {
                float scaleFactor = (1 - position) * (1 - mMinScale) + mMinScale;
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);
                view.setPivotX(pageWidth * ((1 - position) * DEFAULT_CENTER));

            }
        } else {
            view.setPivotX(0f);
            view.setScaleX(mMinScale);
            view.setScaleY(mMinScale);

        }
    }
}

主页面:

package com.loaderman.viewpage2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.CompositePageTransformer;
import androidx.viewpager2.widget.MarginPageTransformer;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

/*
ViewPager2与ViewPager同是继承自ViewGrop,但是ViewPager2被声明成了final。
意味着我们不可能再像ViewPager一样通过继承来修改ViewPager2的代码。
FragmentStatePagerAdapter被FragmentStateAdapter 替代PagerAdapter被RecyclerView.Adapter替代addPageChangeListener被registerOnPageChangeCallback。
我们知道ViewPager的addPageChangeListener接收的是一个OnPageChangeListener的接口,
而这个接口中有三个方法,当想要监听页面变化时需要重写这三个方法。
而ViewPager2的registerOnPageChangeCallback方法接收的是一个叫OnPageChangeCallback的抽象类,
因此我们可以选择性的重写需要的方法即可。移除了setPargeMargin方法。
* */
public class MainActivity extends AppCompatActivity {

    private ViewPager2 viewPager2;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager2 = findViewById(R.id.view_pager);
        btn = findViewById(R.id.btn);
//        MyAdapter myAdapter = new MyAdapter();
        //竖直滑动
//        viewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
//        viewPager2.setAdapter(myAdapter);
        // 页面滑动事件监听
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                System.out.println("onPageScrolled" + +position);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                System.out.println("onPageSelected " + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                System.out.println("onPageScrollStateChanged  state-->" + +state);
            }
        });
        // 设置页面间距
        viewPager2.setPageTransformer(new MarginPageTransformer((int) getResources().getDimension(R.dimen.dp10)));
        //按钮点击可以模拟用户滑动
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //禁止ViewPager2的滑动
                viewPager2.setUserInputEnabled(false);
                //拖拽,按钮点击可以模拟用户滑动
                viewPager2.beginFakeDrag();
                if (viewPager2.fakeDragBy(-310f))
                    viewPager2.endFakeDrag();
            }
        });
        // 设置页面切换动画
        CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
        compositePageTransformer.addTransformer(new ScaleInTransformer());
        compositePageTransformer.addTransformer(new MarginPageTransformer((int) getResources().getDimension(R.dimen.dp10)));
        viewPager2.setPageTransformer(compositePageTransformer);
        //ViewPager2与Fragment 结合使用
        viewPager2.setAdapter(new MyFragmentStateAdapter(this));
        viewPager2.setOffscreenPageLimit(3);

    }
}
FragmentFactory
package com.loaderman.viewpage2;


import androidx.fragment.app.Fragment;

import java.util.HashMap;

public class FragmentFactory {
    private static HashMap<Integer, Fragment> savedFragment = new HashMap<Integer, Fragment>();
    public static Fragment getFragment(int position) {
        Fragment fragment = savedFragment.get(position);
        if (fragment == null) {
            switch (position) {
                case 0:
                    fragment = new Home1Fragment();
                    break;
                case 1:
                    fragment = new Home2Fragment();
                    break;
                case 2:
                    fragment = new Home3Fragment();
                    break;
                case 3:
                    fragment = new Home4Fragment();
                    break;
            }
            savedFragment.put(position, fragment);
        }
        return fragment;
    }
}
package com.loaderman.viewpage2;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Home1Fragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        TextView tv  =  new TextView(getContext());
        tv.setText("Home1Fragment");
        tv.setBackgroundColor(Color.RED);
        return tv;
    }
}

效果:

Android ViewPager2 可垂直左右滑动使用【java】


学习参考:https://juejin.im/post/5df4aabe6fb9a0161104c8eb 【kotlin学习参考】


 

上一篇:android开发导包升级到androidx踩坑记录【转载】


下一篇:无法迁移到androidX