說明:
ViewPager用于實現(xiàn)多頁面的切換效果寞秃,該類存在于Google的兼容包里面掌栅,所以在引用時記得在BuilldPath中加入“android-support-v4.jar”
主布局文件
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" >
<android.support.v4.view.PagerTitleStrip
android:id="@+id/pagertitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top" />
</android.support.v4.view.ViewPager>
</LinearLayout>
其中ViewPager為多頁顯示控件,PagerTitleStrip用于顯示當前頁面的標題
主窗口代碼:
PagerTitleDemoActivity.java
package com.ns.pager;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
public class PagerTitleDemoActivity extends Activity {
/** Called when the activity is first created. */
private ViewPager mViewPager;
private PagerTitleStrip mPagerTitleStrip;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mViewPager = (ViewPager)findViewById(R.id.viewpager);
mPagerTitleStrip = (PagerTitleStrip)findViewById(R.id.pagertitle);
//將要分頁顯示的View裝入數(shù)組中
LayoutInflater mLi = LayoutInflater.from(this);
View view1 = mLi.inflate(R.layout.view1, null);
View view2 = mLi.inflate(R.layout.view2, null);
View view3 = mLi.inflate(R.layout.view3, null);
//每個頁面的Title數(shù)據(jù)
final ArrayList<View> views = new ArrayList<View>();
views.add(view1);
views.add(view2);
views.add(view3);
final ArrayList<String> titles = new ArrayList<String>();
titles.add("tab1");
titles.add("tab2");
titles.add("tab3");
//填充ViewPager的數(shù)據(jù)適配器
PagerAdapter mPagerAdapter = new PagerAdapter() {
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public int getCount() {
return views.size();
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager)container).removeView(views.get(position));
}
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
@Override
public Object instantiateItem(View container, int position) {
((ViewPager)container).addView(views.get(position));
return views.get(position);
}
};
mViewPager.setAdapter(mPagerAdapter);
}
}