1.導包:匯入viewpager包(4.0版本以上已自帶)/或者使用viewpager2
implementation 'androidx.viewpager2:viewpager2:1.1.0-alpha01'
主要流程:佈局檔案新增viewpage控制元件 以及 自定義Layout控制元件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="#ccc"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<requestFocus />
</androidx.viewpager.widget.ViewPager>
<com.example.viewpager.BottomLinulayout
android:id="@+id/btx"
android:layout_width="match_parent"
android:layout_marginTop="600dp"
android:layout_height="wrap_content" />
</RelativeLayout>
viewpager2可以新增滑動方向(豎直或水平)
package com.example.viewpager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
int currentItem;
ArrayList<View> views = new ArrayList<View>(); private static final int[] pics = { R.layout.layout1,
R.layout.layout2, R.layout.layout3};//初始化圖片資源,建立XML檔案顯示引導頁
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViewPager();
}
private void initViewPager() {
ViewPager viewPager =(ViewPager)findViewById(R.id.viewpager);
for (int i = 0; i < pics.length; i++) {
View view = LayoutInflater.from(this).inflate(pics[i], null);
if (i == pics.length - 1) {
Button btt = view.findViewById(R.id.jr);//**重點:這裡必須新增view來繫結控制元件,否則會空指標**
btt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
});
}
views.add(view);//list新增頁面
}
final BottomLinulayout bt=findViewById(R.id.btx);//繫結小圓點控制元件
bt.initViews(views.size(),30,2);//引數:圓點個數、高度、間距
MYViewPageAdapter adapter = new MYViewPageAdapter();
adapter.setViews(views);//設定介面卡引數
viewPager.setAdapter(adapter);//設定介面卡
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if(bt != null){
bt.changePosition(position);//當頁面改變後改變圓點位置,通過view的position同步
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
viewPager.setOnTouchListener(new View.OnTouchListener() {
float startX;
float startY;
float endX;
float endY;
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN://當觸控按下
startX=event.getX();
startY=event.getY();
break;
case MotionEvent.ACTION_UP://當觸控擡起來
endX=event.getX();
endY=event.getY();
WindowManager windowManager= (WindowManager) getApplicationContext().getSystemService(MainActivity.this.WINDOW_SERVICE);
//獲取螢幕的寬度
Point size = new Point();
windowManager.getDefaultDisplay().getSize(size);
int width=size.x;
//首先要確定的是,是否到了最後一頁,然後判斷是否向左滑動,並且滑動距離是否符合,我這裡的判斷距離是螢幕寬度的4分之一(這裡可以適當控制)
if(currentItem==(views.size()-1)&&startX-endX>0&&startX-endX>=(width/4)){
// goToMainActivity();//跳轉頁面
overridePendingTransition(R.xml.slide_in_right,R.xml.slide_in_left);//實現兩個 Activity 切換時的動畫。左滑 右滑,通過xml進行動畫編輯
}
break;
} return false;
}
});
}
private void goToMainActivity() {
Intent intent=new Intent(this,Main2Activity.class);
startActivity(intent);
}
}
其中,需要自定義介面卡,繼承pageadpter:
package adpter;
import android.view.View;
import android.widget.BaseAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import java.util.ArrayList;
public class MYViewPageAdapter extends PagerAdapter {
private ArrayList<View> views;
public void setViews(ArrayList<View> views){
this.views = views;
}
@Override
public int getCount() {
return views.size();
}//返回view個數
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager)container).removeView(views.get(position));
}//刪除頁面
@Override
public Object instantiateItem(View container, int position) {
((ViewPager) container).addView(views.get(position));
return views.get(position);//生成頁面
}
}
小圓點的自定義佈局檔案:
package com.example.viewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
public class BottomLinulayout extends LinearLayout {
private int itemDefaultBgResId = R.drawable.normal;//單個元素預設背景樣式
private int itemSelectedBgResId = R.drawable.select;//單個元素選中背景樣式
private int currentPosition;//當前選中位置
private int itemHeight = 50;//item寬高
private int itemMargin = 5;//item間距
public BottomLinulayout(Context context) {
this(context, null, 0);
}
public BottomLinulayout(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomLinulayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOrientation(HORIZONTAL);
setGravity(Gravity.CENTER);
}
public void initViews(int count, int itemHeight, int itemMargin) {//設定小圓點
this.itemHeight = itemHeight;
this.itemMargin = itemMargin;
removeAllViews();//每次建立移除views
if(count == 0 || itemHeight == 0){
return;
}
View view = createView(itemHeight,itemMargin);//建立一個view
view.setBackgroundResource(itemSelectedBgResId);//設定當前選中的樣式
addView(view);//將view新增到佈局中
if(count == 1){
return;//如果只有一個 不必生成未選中的圖
}
for (int i = 1; i < count; i++) {
view = createView(itemHeight,itemMargin);
view.setBackgroundResource(itemDefaultBgResId);//生成未選中的樣式
addView(view);
}
}
/**
* 建立view
* @param sideLength 邊長
* @param itemMargin 外間距
* @return
*/
public View createView(int sideLength,int itemMargin){
TextView textview = new TextView(getContext());
LinearLayout.LayoutParams params = new LayoutParams(sideLength, sideLength);//LayoutParams 是 ViewGroup 的一個內部類,這是一個基礎類別,
if(itemMargin > 0){
params.setMargins(itemMargin,0,itemMargin,0);
}
textview.setLayoutParams(params);//設定textview的Parms
return textview;
}
public void changePosition(int position) {//改變選中的view
if(getChildCount() <= 1){
return;
}
getChildAt(currentPosition).setBackgroundResource(itemDefaultBgResId);
currentPosition = position % getChildCount();
getChildAt(currentPosition).setBackgroundResource(itemSelectedBgResId);
}
}
小圓點實心或者空心檔案,通過shape檔案控制
//空心
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">//shape設定形狀 oval為橢圓 rectangle(矩形),ov,line(線形),ring(圓環)
<solid android:color="#fff"/>//設定填充色
<size
android:width="10dp"//設定寬
android:height="10dp"></size>
<stroke android:color="#ccc" android:width="1dp"/>
</shape>
```java
//實心
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/cardview_dark_background"/>
<size
android:width="9dp"
android:height="9dp"></size>
<!--<stroke android:color="#fff" android:width="1dp"/>-->
</shape>