大多數的APP都可以實現幾個屏幕來回的切換,
首先新建兩個Activity,內容隨意,布局隨意。接下來在MainActivity.xml:
復制代碼
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 tools:context=".MainActivity" >
6
7 <android.support.v4.view.ViewPager
8 android:id="@+id/viewpager"
9 android:layout_width="wrap_content"
10 android:layout_height="wrap_content" >
11 </android.support.v4.view.ViewPager>
12
13 </RelativeLayou
復制代碼
不要忘記android-support-v4包,目前4.0以上版本都自帶
接下來是java中的方法:
復制代碼
1 protected void onCreate(Bundle savedInstanceState) {
2 super.onCreate(savedInstanceState);
3 setContentView(R.layout.activity_main);
4 viewPager = (ViewPager) findViewById(R.id.viewpager);
5 View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.a,
6 null);
7 View view2 = LayoutInflater.from(MainActivity.this).inflate(R.layout.b,
8 null);
9 list = new ArrayList<View>();
10 list.add(view1);
11 list.add(view2);
12 viewPager.setAdapter(new MyAdapter());
13 }
復制代碼
復制代碼
1 class MyAdapter extends PagerAdapter {
2
3 @Override
4 public int getCount() {
5 return list.size();
6 }
7
8 @Override
9 public boolean isViewFromObject(View arg0, Object arg1) {
10 return arg0 == arg1;
11 }
12
13 @Override
14 public CharSequence getPageTitle(int position) {
15 return titlelist.get(position);
16
17 }
18
19 @Override
20 public Object instantiateItem(View container, int position) {
21 ((ViewPager) container).addView(list.get(position));
22 return list.get(position);
23 }
24
25 @Override
26 public void destroyItem(View container, int position, Object object) {
27 super.destroyItem(container, position, object);
28 ((ViewPager) container).removeView(list.get(position));
29 }
30 }