安卓开发--页面左右滑动
本次博客演示三个页面之间的滑动切换,利用ViewPager2实现,最终的文件目录结构如下:
app/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── myapp/
│ │ │ ├── HomeActivity.java
│ │ │ └── fragments/
│ │ │ ├── ViewPagerAdapter.java
│ │ │ ├── WebViewFragment.java
│ │ │ ├── LayoutFragment.java
│ │ │ └── OtherFragment.java
│ │ ├── res/
│ │ │ ├── layout/
│ │ │ │ ├── activity_home.xml
│ │ │ │ ├── fragment_webview.xml
│ │ │ │ ├── fragment_layout.xml
│ │ │ │ └── fragment_other.xml
│ │ │ └── ...
│ │ └── AndroidManifest.xml
├── ...
1.在布局文件中定义ViewPager2
这是一个主布局文件res/layout/activity_home.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"
android:orientation="horizontal">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
2.三个子切换页面的布局代码以及效果
文件一 res/layout/fragment_layout.xml
,代码如下,显示的是一个折线图:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
文件二 res/layout/fragment_layout.xml
,代码如下,显示的是一个文本框:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<!-- 其他布局内容 -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="这是一个其他布局"
android:textSize="50dp"/>
</FrameLayout>
文件三res/layout/fragment_other.xml
,代码如下,显示的是一个GIF动图:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/gif_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
</FrameLayout>
其各自效果如图:
文件1 | 文件2 | 文件3 |
---|---|---|
![]() |
![]() |
![]() |
3.三个切换页面的活动文件代码
文件一 java/com/example/ecgphone/fragments/WebViewFragment.java
,代码如下,显示的是一个折线图:
package com.example.ecgphone.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View