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

时间:2023-12-31 09:16:38

大多数的APP都可以实现几个屏幕来回的切换,

首先新建两个Activity,内容随意,布局随意。接下来在MainActivity.xml:

 <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"
tools:context=".MainActivity" > <android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</android.support.v4.view.ViewPager> </RelativeLayou
不要忘记android-support-v4包,目前4.0以上版本都自带

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

接下来是java中的方法:
 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.a,
null);
View view2 = LayoutInflater.from(MainActivity.this).inflate(R.layout.b,
null);
list = new ArrayList<View>();
list.add(view1);
list.add(view2);
viewPager.setAdapter(new MyAdapter());
}
 class MyAdapter extends PagerAdapter {

         @Override
public int getCount() {
return list.size();
} @Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
} @Override
public CharSequence getPageTitle(int position) {
return titlelist.get(position); } @Override
public Object instantiateItem(View container, int position) {
((ViewPager) container).addView(list.get(position));
return list.get(position);
} @Override
public void destroyItem(View container, int position, Object object) {
super.destroyItem(container, position, object);
((ViewPager) container).removeView(list.get(position));
}
}

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