Basic usage of viewpager component in Android and an example of image switching

Viewpager is a component in the android-support-v4.jar package. In the layout file, the label needs to be combined with the package name

Write full name < Android. Support. V4. View. Viewpager / >

Basic Usage

The basic usage of viewpager can be summarized into three steps

The first step is to put a viewpager component in the main layout file

The second step is to create a layout file for each page and write the interface well

Step 3: get the viewpager component in the main activity and set the adapter for it.

Adapter. The adapter corresponding to viewpager inherits from pageradapter,

It is also in the android.support.v4.view package. The inheritance class needs to implement four methods:

First, we use layoutinflator to load the interface previously established for each page and put it in a container such as ArrayList. Then, in the four methods of pageradapter, we operate the view corresponding to these pages.

Using the viewpager component to realize picture switching, the above steps may sound empty. Let's take a look at this example of using the viewpager component to realize picture switching: in many apps, especially after the first installation and startup, several pictures will appear to introduce and explain the app, and the pictures can be switched with sliding.

Here we use the viewpager component to demonstrate how to do this.

1. Create an app project and create a main activity by default

2. Set the layout file activity of the activity_ Main.xml is as follows:

Because we want to switch the picture, there can be some dot shaped icons (or numbers) to display the current picture. Therefore, the activity here adopts the FrameLayout layout (view overlapping placement can be realized).

The first control is viewpager (note that viewpager is in the support.v4 package, and this component is not ported in the new Android).

The second control is to place a relativelayout, in which a LinearLayout (located at the bottom of the screen) is placed. The LinearLayout adopts a horizontal layout to place small icons.

3. Prepare pictures

Prepare 5 pictures for switching display, such as pic1.jpg, pic2.jpg, pic3.jpg, pic4.jpg and pic5.jpg, and then prepare two small icon Pictures_ current.png、page_ not_ current.png。

Put these pictures in the drawable hdpi directory (or the drawable directory of the corresponding size).

4. Write code for activity

5. If you need not to display the title bar of the activity, you can modify the configuration in the activity in the manifest to set the style as:

Other configuration files, code, etc. are default settings created by eclipse.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>