ViewPager in Android allows the user to flip left and right through pages of data. In our android ViewPager application we’ll implement a ViewPager that swipes through three views with different images and texts.

Android中的ViewPager允许用户在数据页面之间左右翻转。 在我们的Android ViewPager应用程序中,我们将实现一个ViewPager,该控件可在具有不同图像和文本的三个视图之间滑动。

Android ViewPager (Android ViewPager)

Android ViewPager widget is found in the support library and it allows the user to swipe left or right to see an entirely new screen.

在支持库中找到了Android ViewPager小部件,它允许用户向左或向右滑动以查看全新的屏幕。

Today we’re implementing a ViewPager by using Views and PagerAdapter. Though we can implement the same using Fragments too, but we’ll discuss that in a later tutorial.

今天,我们通过使用ViewsPagerAdapter来实现ViewPager 。 尽管我们也可以使用Fragments实现相同的功能,但是我们将在以后的教程中进行讨论。

The ViewPager uses a PagerAdapter whose job is to supply views to the MainActivity similar to what a ListAdapter does for a ListView.

ViewPager使用PagerAdapter,其工作是向MainActivity提供视图,类似于ListAdapter对ListView所做的操作。

Android ViewPager示例 (Android ViewPager Example)

Android ViewPager示例代码 (Android ViewPager Example Code)

The activity_main.xml consists solely of the ViewPager as shown below.

activity_main.xml仅由ViewPager组成,如下所示。

activity_main.xml

activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:tools="https://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><android.support.v4.view.ViewPagerandroid:id="@+id/viewpager"android:layout_width="match_parent"android:layout_height="match_parent"/></RelativeLayout>

The MainActivity.java is given below.

MainActivity.java在下面给出。

MainActivity.java

MainActivity.java

package com.journaldev.viewpager;import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);viewPager.setAdapter(new CustomPagerAdapter(this));}
}

The role of the MainActivity in the above code is to just reference the ViewPager and set the CustomPagerAdapter that extends the PagerAdapter.

上面的代码中MainActivity的作用是仅引用ViewPager并设置CustomPagerAdapter来扩展PagerAdapter

Before we discuss the CustomPagerAdapter class, let’s look into the ModelObject class.

在讨论CustomPagerAdapter类之前,让我们研究一下ModelObject类。

ModelObject.java

ModelObject.java

package com.journaldev.viewpager;public enum ModelObject {RED(R.string.red, R.layout.view_red),BLUE(R.string.blue, R.layout.view_blue),GREEN(R.string.green, R.layout.view_green);private int mTitleResId;private int mLayoutResId;ModelObject(int titleResId, int layoutResId) {mTitleResId = titleResId;mLayoutResId = layoutResId;}public int getTitleResId() {return mTitleResId;}public int getLayoutResId() {return mLayoutResId;}}

The enum above lists all the pages of the ViewPagers. There are three pages with their respective layouts.

上面的枚举列出了ViewPagers的所有页面。 共有三页,分别有各自的布局。

The layout of a single page is given below.

单个页面的布局如下。

view_blue.xml

view_blue.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:background="@android:color/holo_blue_dark"android:layout_height="match_parent"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Second View"android:layout_gravity="center_horizontal"android:textSize="28sp"android:textColor="@android:color/black"android:textStyle="bold"android:layout_centerVertical="true"android:layout_centerHorizontal="true"android:id="@+id/textView" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Swipe left to\nFirst View"android:layout_gravity="center_horizontal"android:textSize="20sp"android:textColor="@android:color/black"android:textStyle="bold"android:minLines="2"android:id="@+id/textView2"android:padding="@dimen/activity_horizontal_margin"android:layout_alignParentBottom="true"android:layout_alignParentLeft="true"android:layout_alignParentStart="true" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Swipe right to\nThird View"android:layout_gravity="center_horizontal"android:textSize="20sp"android:textColor="@android:color/black"android:textStyle="bold"android:padding="@dimen/activity_horizontal_margin"android:minLines="2"android:id="@+id/textView3"android:layout_alignTop="@+id/textView2"android:layout_alignParentRight="true"android:layout_alignParentEnd="true" /></RelativeLayout>

The remaining two pages have similar layouts and are given in the source code of this project.

其余两个页面具有相似的布局,并在该项目的源代码中给出。

CustomPagerAdapter.java

CustomPagerAdapter.java

package com.journaldev.viewpager;import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;public class CustomPagerAdapter extends PagerAdapter {private Context mContext;public CustomPagerAdapter(Context context) {mContext = context;}@Overridepublic Object instantiateItem(ViewGroup collection, int position) {ModelObject modelObject = ModelObject.values()[position];LayoutInflater inflater = LayoutInflater.from(mContext);ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);collection.addView(layout);return layout;}@Overridepublic void destroyItem(ViewGroup collection, int position, Object view) {collection.removeView((View) view);}@Overridepublic int getCount() {return ModelObject.values().length;}@Overridepublic boolean isViewFromObject(View view, Object object) {return view == object;}@Overridepublic CharSequence getPageTitle(int position) {ModelObject customPagerEnum = ModelObject.values()[position];return mContext.getString(customPagerEnum.getTitleResId());}}
  1. CustomPagerAdapter(Context context) : The constructor needs a Context reference. The context is saved as a member variable of the class since it’s used later to access the individual page layouts from the enum classCustomPagerAdapter(Context context) :构造函数需要一个Context引用。 上下文被保存为该类的成员变量,因为以后将使用它来访问enum类中的各个页面布局
  2. instantiateItem : In this case, we use the enum and inflate the particular enum value’s associated layout. Then, we add the newly inflated layout to the ViewGroup(collection of Views) maintained by the PagerAdapter, and then we return that layout. The object being returned by this method is also used later on, as the second parameter in the isViewFromObject methodInstantiateItem :在这种情况下,我们使用枚举并为特定的枚举值关联的布局充气。 然后,将新膨胀的布局添加到PagerAdapter维护的ViewGroup(视图集合)中,然后返回该布局。 此方法返回的对象稍后也将用作isViewFromObject方法中的第二个参数
  3. destroyItem : This method removes a particular view from the ViewGroup maintained by the PagerAdapterdestroyItem :此方法从PagerAdapter维护的ViewGroup中删除特定视图
  4. getCount : It simply returns the number of views that will be maintained by the ViewPager. For this example, the count is the number of enum values in the model objectgetCount :它只是返回将由ViewPager维护的视图数。 对于此示例,计数是模型对象中枚举值的数量
  5. isViewFromObject : This method checks whether a particular object belongs to a given position, which is made simple. As noted earlier, the second parameter is of type Object and is the same as the return value from the instantiateItem methodisViewFromObject :此方法检查特定对象是否属于给定位置,这很简单。 如前所述,第二个参数的类型为Object,并且与instantiateItem方法的返回值相同。
  6. getPageTitle : At a given position, we need to supply the PagerAdapter with a title. This usually manifests itself in the ActionBar as the Activity’s title, or sometimes tabs will hook into this method for labelling each tab. In this case we’ve kept it for labelling onlygetPageTitle :在给定位置,我们需要为PagerAdapter提供标题。 通常,这会在ActionBar中显示为Activity的标题,或者有时标签会挂接到此方法中以标记每个标签。 在这种情况下,我们保留它仅用于标记

The image below shows the app in action.

下图显示了正在运行的应用程序。

This brings an end to ViewPager in android example tutorial. You can download the Android ViewPager Project from the below link.

这结束了Android示例教程中的ViewPager。 您可以从下面的链接下载Android ViewPager项目。

Download Android ViewPager Example Project下载Android ViewPager示例项目

翻译自: https://www.journaldev.com/10096/android-viewpager-example-tutorial

Android ViewPager示例教程相关推荐

  1. Android WebView示例教程

    Android WebView is used to display HTML in an android app. We can use android WebView to load HTML p ...

  2. Android ExpandableListView示例教程

    Welcome to Android ExpandableListView Example Tutorial. In this tutorial we'll implement an Expandab ...

  3. Android ListView示例教程

    We will learn how to create a simple Android ListView and launch a new activity on selecting a singl ...

  4. Android ActionBar示例教程

    Today we will look into Android ActionBar. Action Bar is one of the important part of any applicatio ...

  5. 使用DataBinding的Android SearchView示例教程

    Today we will look into Android SearchView widget and develop an application that filters a ListView ...

  6. Android AsyncTask示例教程

    Today we will look into Android AsyncTask. We will develop an Android example application that perfo ...

  7. Android BroadcastReceiver示例教程

    Today we'll discuss and implement Android BroadcastReceiver that is a very important component of An ...

  8. android jni示例_Android动画示例

    android jni示例 Android Animation is used to give the UI a rich look and feel. Animations in android a ...

  9. Android ProgressDialog示例

    Welcome to Android ProgressDialog Example. In this tutorial we'll learn how to create Android Progre ...

最新文章

  1. 【转】ASP.NET中“字母和数字混合的验证码”详解
  2. MYSQL-使用mysqldump创建数据库快照
  3. 用投资的观点学习编程
  4. html手机端页面meta,手机页面的 HTMLmeta 标签使用与说明
  5. TSS详解 ——《x86汇编语言:从实模式到保护模式》读书笔记33
  6. 简单了解Python网络爬虫
  7. leetcode 198. 打家劫舍(最简单的动态规划问题)
  8. 中考计算机IE操作题,信息技术中考历年真题集锦(IE操作)
  9. 老年计算机音乐,老年音乐影集相机V1.2.5
  10. WPF效果(GIS三维篇)
  11. Oracle宣布新的Java Champions
  12. 怎么把项目的数据上传到服务器,怎么把sql数据库上传到云服务器
  13. 小米再被质疑Mimoji抄袭苹果 回应:上传出错 将严肃处理
  14. python字典有什么用_Python中的字典介绍
  15. python 读取json与xml格式化等处理
  16. MapABC 地图定位
  17. 方舟手游怎么在服务器用gg修改器,方舟手游gg修改器脚本
  18. jQuery 利用 :even 和 :odd偶数奇数 进行变色
  19. 一块蛋清皂,把毛孔洗得一干二净
  20. 良心教程教你如何使用Excel简单绘制数据图表。

热门文章

  1. 技术专题之-技术概述的目录
  2. 【原创翻译】深入理解javascript事件处理函数绑定三部曲(一)——早期的事件处理函数...
  3. ArcGIS API for Silverlight/WPF/Windows Phone/Android 插件下载地址
  4. [转载] 机器学习 scikit-learn1 预测贷款用户是否会逾期
  5. [转载] python函数——字典设置默认值get() 与 setdefault()区别
  6. [转载] 深层复制构造函数和浅层复制构造函数区别
  7. [转载] 在Python中使用Matplotlib绘制常见图表
  8. hdu1113 Word Amalgamation(详解--map和string的运用)
  9. Chapter 7 代理模式
  10. PHP 输入一棵二叉树和一个数字n,要求找出路径和为n的所有路径