几乎在现在的所有主流App中,都能左右滑动切换页面。在学习过后,知道了这是一种控件做出来的效果,他就是ViewPager。
VeiwPager是扩展包support.v4中的控件,因此要使用它,需要在libs目录下导入android-support-v4.jar包。我们可以通过一个简单的例子来熟悉它的用法:
新建一个项目ViewPager,在libs文件夹下导入需要的jar包。
首先在布局文件中定义一个ViewPager:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_viewPager"
>
</android.support.v4.view.ViewPager>
</RelativeLayout>
新建三个布局以显示效果:
只是简单的例子,用的是三个只有背景的布局
布局1:page1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#777777">
</LinearLayout>
布局2:page2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#cdcdcd">
</LinearLayout>
布局3:page3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#114490">
</LinearLayout>
接着是代码部分:
public class MainActivity extends Activity {
//存放所有要显示的View
private List<View> pages;
private ViewPager viewPager;
//为ViewPager添加的PagerAdapter
private PagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.main_viewPager);
LayoutInflater inflater = getLayoutInflater();
View page1 = inflater.inflate(R.layout.page1, null);
View page2 = inflater.inflate(R.layout.page2, null);
View page3 = inflater.inflate(R.layout.page3,null);
//将所有的View添加到List中
pages = new ArrayList<View>();
pages.add(page1);
pages.add(page2);
pages.add(page3);
adapter = new PagerAdapter() {
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
container.removeView((View)object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
container.addView(pages.get(position));;
return pages.get(position);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0==arg1;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return pages.size();
}
};
//为viewPager设置Adapter
viewPager.setAdapter(adapter);
}
}
从以上代码可以得出使用ViewPager的几个步骤:
1、在布局文件中定义ViewPager
2、在代码中将ViewPager和要显示的东西创建出来
3、创建适配器PagerAdapter
4、为ViewPager设置Adapter
本例的效果图:
第一个页面滑动到第二个页面:
第二个页面滑动到第三个页面: