Android用viewPager2實現UI界面翻頁滾動的效果

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>

最終效果圖:

以上就是Android用viewPager2實現UI界面翻頁滾動的效果的詳細內容,更多關於Android UI界面翻頁滾動的資料請關註WalkonNet其它相關文章!

推薦閱讀: