Paste_Image.png 说明: ViewPager用于实现多页面的切换效果,该类存在于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装入数组中 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数据 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的数据适配器 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); } }(责任编辑:好模板) |