Basic usage of ViewPager component in Android and examples of picture switching

  • 2021-06-28 13:55:04
  • OfStack

ViewPager is a component of the android-support-v4.jar package.Labels need to be packaged together in the layout file

Write the full name < android.support.v4.view.ViewPager / >

Basic Usage

The basic usage of ViewPager is summarized in three steps

Step 1 Place an ViewPager component in the main layout file

Step 2: Create a layout file for each page and write the interface

Step 3 takes the ViewPager component in the main Activity and sets the Adapter for it.

Adapter elaborates that the Adapter corresponding to ViewPager is inherited from PagerAdapter.

Also in the android.support.v4.view package, inheritance classes need to implement four methods:

int getCount (): Number of returned pages Object instantiateItem (ViewGroup, int position): Create a page view of the position location, add it to ViewGroup, and return the Key of that view.Key can be this view or other only 1 object corresponding to this view: boolean isViewFromObject (View, Object): Determines whether the Key represented by Object corresponds to the specified View. void destroyItem (ViewGroup, int position, Object): Remove View from ViewGroup at the position location.

First, we use LayoutInflater to load the interface we created for each page and place it in a container like ArrayList.Then in these four methods of PagerAdapter, what we do is View corresponding to these pages.

Picture Switching Using ViewPager Component
These steps may sound empty, but here's an example of switching pictures using the ViewPager component:
In many Apps, especially after the first installation is started, several pictures will appear for the introduction and explanation of app, which 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 master Activity by default

2. Set the layout file activity_for this Activitymain.xml is as follows:


<?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="vertical" >
   
  <android.support.v4.view.ViewPager 
    android:id="@+id/viewPager" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" />
     
  <RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"
    android:orientation="vertical" > 
  
    <LinearLayout 
      android:id="@+id/tagView" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_alignParentBottom="true"
      android:layout_marginBottom="20dp" 
      android:gravity="center_horizontal" 
      android:orientation="horizontal" > 
    </LinearLayout> 
  </RelativeLayout> 
 
</FrameLayout>

Because we want to switch pictures again, an icon (or a number) with a dot shape can display the current picture.So here, activity uses the FrameLayout layout (which enables overlapping placement of view).

The first control is ViewPager (note that ViewPager is in the support.v4 package and is not ported in the new andorid).

The second control is to place an RelativeLayout with an LinearLayout (at the bottom of the screen) in a horizontal layout for small icons.

3. Prepare pictures

Prepare five pictures for switching display, such as pic1.jpg, pic2.jpg, pic3.jpg, pic4.jpg, pic5.jpg, and two small icon Pictures page_current.png, page_not_current.png.

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

4. Write code for activity


package com.example.showviewpager;
 
import java.util.ArrayList;
 
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
 
public class MainActivity extends Activity {
 
  private static final int VIEW_NUM = 5;
  private ViewPager viewPager;
  private ImageView[] tagImageViews = new ImageView[VIEW_NUM];
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    addTagImage();
    initViewPager();
  }
 
  private void addTagImage() {
    LinearLayout layout = (LinearLayout)findViewById(R.id.tagView);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    params.setMargins(15, 0, 0, 0);
    for (int i = 0; i < VIEW_NUM; i++) {
      ImageView tagImageView = new ImageView(this);
      tagImageView.setLayoutParams(params);
      tagImageViews[i] = tagImageView;
      if (i == 0) {
        tagImageView.setBackgroundResource(R.drawable.page_current);
      } else {
        tagImageView.setBackgroundResource(R.drawable.page_not_current);
      }
 
      layout.addView(tagImageView);
    }
  }
   
  private void initViewPager() {
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    viewPager.setAdapter(new MyAdapter());
    viewPager.setOnPageChangeListener(new OnPageChangeListener() {
      @Override
      public void onPageSelected(int arg0) {
        for (int i = 0; i < tagImageViews.length; i++) {
          if (i == arg0 % VIEW_NUM) {
            tagImageViews[i].setBackgroundResource(R.drawable.page_current);
          } else {
            tagImageViews[i].setBackgroundResource(R.drawable.page_not_current);
          }
        }
      }
       
      @Override
      public void onPageScrolled(int arg0, float arg1, int arg2) {
         
      }
       
      @Override
      public void onPageScrollStateChanged(int arg0) {
         
      }
    });
    viewPager.setCurrentItem(0);
  }
   
  class MyAdapter extends PagerAdapter{
    private ArrayList<View> viewList;
    public MyAdapter(){
      viewList = new ArrayList<View>();
      viewList.add(createPagerImageView(R.drawable.pic1));
      viewList.add(createPagerImageView(R.drawable.pic2));
      viewList.add(createPagerImageView(R.drawable.pic3));
      viewList.add(createPagerImageView(R.drawable.pic4));
      viewList.add(createPagerImageView(R.drawable.pic5));
    }
     
    private View createPagerImageView(int resid){
      LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
      LinearLayout layout = new LinearLayout(MainActivity.this);
      layout.setLayoutParams(params);
      layout.setOrientation(LinearLayout.VERTICAL);
      ImageView imageView = new ImageView(MainActivity.this);
      imageView.setLayoutParams(params);
      imageView.setScaleType(ScaleType.CENTER_CROP);
      imageView.setImageResource(resid);
      layout.addView(imageView);
      return layout;
    }
     
    @Override
    public int getCount() {
      return Integer.MAX_VALUE;
    }
 
    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
      return arg0 == arg1;
    }
     
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
      ((ViewPager) container).addView(viewList.get(position % VIEW_NUM),0);
      return viewList.get(position % VIEW_NUM);
    }
 
    @Override
    public void destroyItem(View container, int position, Object object) {
      ((ViewPager) container).removeView(viewList
          .get(position % VIEW_NUM));
    }
     
  }
 
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }
 
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
      return true;
    }
    return super.onOptionsItemSelected(item);
  }
}

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


android:theme="@android:style/Theme.Black.NoTitleBar" 


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.showviewpager"
  android:versionCode="1"
  android:versionName="1.0" >
 
  <uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="21" />
 
  <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
      android:name=".MainActivity"
      android:label="@string/app_name"
      android:theme="@android:style/Theme.Black.NoTitleBar" >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
 
</manifest>

*

Other profiles, code, and so on are default settings created using eclipse.


Related articles: