android中viewPager实现的屏幕左右切换(入门篇)

时间:2022-11-24 14:43:25

大多数的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以上版本都自带

android中viewPager实现的屏幕左右切换(入门篇)

接下来是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     }

至此就可以实现两个屏幕的切换