源博文链接:http://blog.sina.com.cn/s/blog_a69672d901017nox.html
一、实现多面界面滑动切换方法有多种,就目前我所知道的大致有三种:
1.ViewFlipper + Animation:
2.ViewGroup + Scroller + VelocityTracker
3.ViewPager
本文主要介绍第三种ViewPager实现方式
二、ViewPager是google Android SDk中自带的一个附加包(android-support-v4.jar)的一个类可以用来实现屏幕间的切换。如下图:
如果在工程中没有看见该附加包,请及时更新sdk,并勾选Extras/Android Support Library安装
三、ViewPager的简单使用
创建工程ViewPagerDemo1
1.主布局文件activity_main.xml:
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<requestFocus />
</android.support.v4.view.ViewPager>
</RelativeLayout>
2.子页面布局 layout1,xml,layout2,xml,layout3_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:background="#ff0000ff"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第一页"
android:textColor="#ffffffff"
android:textSize="30sp"/>
</LinearLayout>
本例子三个页面布局一样
3.主窗口代码:
public class MainActivity extends Activity{
@Override
public voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViewPager();
}
private voidinitViewPager(){
ViewPager viewPager =(ViewPager)findViewById(R.id.viewPager);
View view1 =LayoutInflater.from(this).inflate(R.layout.layout1, null);
View view2 =LayoutInflater.from(this).inflate(R.layout.layout2, null);
View view3 =LayoutInflater.from(this).inflate(R.layout.layout3, null);
ArrayList<View>views = new ArrayList<View>();
views.add(view1);
views.add(view2);
views.add(view3);
MYViewPagerAdapter adapter = newMYViewPagerAdapter();
adapter.setViews(views);
viewPager.setAdapter(adapter);
}
}
4.另外还需继承PagerAdapter类实现自己MYPagerAdapter适配器类
publicclass MYViewPagerAdapter extends PagerAdapter {
privateArrayList<View> views;
public voidsetViews(ArrayList<View> views){
this.views = views;
}
@Override
public int getCount() {
return views.size();
}
@Override
public boolean isViewFromObject(View arg0, Objectarg1) {
return arg0 == arg1;
}
@Override
public void destroyItem(View container, intposition, Object object) {
((ViewPager)container).removeView(views.get(position));
}
@Override
public Object instantiateItem(View container, intposition) {
((ViewPager)container).addView(views.get(position));
returnviews.get(position);
}
工程下载地址:http://115.com/file/e75fxvro#ViewPagerDemo1.rar
代码运行效果如下: