码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2014-09-07 14:40:55      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:des   android   style   blog   http   color   os   io   java   

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

bubuko.com,布布扣

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

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

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

标签:des   android   style   blog   http   color   os   io   java   

原文地址:http://www.cnblogs.com/stayreal/p/3960346.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!