Fragment支持在不同的Activity中使用并且可以处理自己的输入事件以及生命周期方法等。可以看做是一个子Activity。
先看一下布局:
1 <LinearLayout 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=".ViewPagerActivity" > 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:layout_gravity="center" > 12 </android.support.v4.view.ViewPager> 13 14 </LinearLayout>
主文件:ViewPagerActivity继承FragmentActivity
1 package com.example.viewpagerdemo; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import android.os.Bundle; 7 import android.support.v4.app.Fragment; 8 import android.support.v4.app.FragmentActivity; 9 import android.support.v4.view.ViewPager; 10 11 import com.example.adapter.fragmentAdapter; 12 13 public class ViewPagerActivity extends FragmentActivity { 14 15 @Override 16 protected void onCreate(Bundle savedInstanceState) { 17 super.onCreate(savedInstanceState); 18 setContentView(R.layout.activity_view_pager); 19 List<Fragment> fragments = new ArrayList<Fragment>(); 20 for (int i = 0; i < 3; i++) { 21 Fragment f = new ButtonFragment(); 22 fragments.add(f); 23 } 24 ViewPager vp = (ViewPager) findViewById(R.id.viewpager); 25 fragmentAdapter fa = new fragmentAdapter(getSupportFragmentManager(), 26 fragments); 27 vp.setAdapter(fa); 28 vp.setCurrentItem(0); 29 } 30 }
新建fragmentAdapter继承FragmentPagerAdapter并未写出实现的方法
1 package com.example.adapter; 2 3 import java.util.List; 4 5 import android.support.v4.app.Fragment; 6 import android.support.v4.app.FragmentManager; 7 import android.support.v4.app.FragmentPagerAdapter; 8 9 public class fragmentAdapter extends FragmentPagerAdapter { 10 private List<Fragment> fragments; 11 private FragmentManager fm; 12 13 public fragmentAdapter(FragmentManager fm, List<Fragment> fragments) { 14 super(fm); 15 this.fragments = fragments; 16 17 } 18 19 public fragmentAdapter(FragmentManager fm) { 20 super(fm); 21 this.fm = fm; 22 } 23 24 @Override 25 public Fragment getItem(int arg0) { 26 return fragments.get(arg0); 27 } 28 29 @Override 30 public int getCount() { 31 return fragments.size(); 32 } 33 34 }
定义要展示的fragment内容,在这只放一个Button
1 package com.example.viewpagerdemo; 2 3 import android.os.Bundle; 4 import android.support.v4.app.Fragment; 5 import android.view.LayoutInflater; 6 import android.view.View; 7 import android.view.ViewGroup; 8 import android.widget.TextView; 9 10 public class ButtonFragment extends Fragment {11 private View rootView;
12 13 @Override 14 public View onCreateView(LayoutInflater inflater, ViewGroup container, 15 Bundle savedInstanceState) { 16 rootView = inflater.inflate(R.layout.guide1, container, false); 17 return rootView; 18 } 19 }
至此实现3个含有Button可以左右切换了