最近在研究ViewPager的使用,我将分段将ViewPager的使用方法和技巧介绍给大家。
基本使用可分为五部完成:
1.ViewPager是谷歌一个向下兼容包(android-support-v4.jar)里面的类,所以要使用它先引入android-support-v4.jar。该jar包一般存在于android SDK目录sdk\extras\android\support\v4下面。
2.然后是布局文件中添加控件:
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<android.support.v4.view.PagerTitleStrip
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</android.support.v4.view.PagerTitleStrip >
</android.support.v4.view.ViewPager>
android.support.v4.view.PagerTitleStrip用来显示顶部标题。3.在activity中找到ViewPager控件和PagerTitleStrip控件:
viewPager = (ViewPager) findViewById(R.id.pager); pagerTitleStrip = (PagerTitleStrip) findViewById(R.id.title);
4.为ViewPager写数据适配器,ViewPage使用的数据适配器是PagerAdapter,所以要自己继承PagerAdapter(抽象
类)写个实现类。
class MyAdapter extends PagerAdapter {
@Override
public int getCount() {
return 5;
}
@Override
public CharSequence getPageTitle(int position) {
return "标题" + position;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
TextView textView = new TextView(MainActivity.this);
textView.setText("内容" + position);
//用代码创建一个layout
LinearLayout layout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
layout.setGravity(Gravity.CENTER);
layout.setLayoutParams(params);
layout.addView(textView);
container.addView(layout);
return layout;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// super.destroyItem(container, position, object);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;// 官方提示这样写
}
}
注意:// super.destroyItem(container, position, object);这行代码一定要注释掉。我将在以后的课程中
介绍PagerAdapter各个方法的作用。
5.绑定数据适配器
viewPager.setAdapter(new MyAdapter());
附加说明:android-support-v4.jar的源码目录是\sdk\extras\android\support\v4\src,我将在以后的课程中给大家介绍怎么在eclipse中查看android-support-v4.jar的源码。
原文地址:http://blog.csdn.net/u013250921/article/details/24597787