Android : Swipe View With Tabs

分成三個步驟


1.在onCreate時候建立ActionBar,ActionBar.addTab增加Tab的頁面,並且在FragmentActivity實作TabListener


2.建立一個class繼承FragmentStatePagerAdapter用來狀載Fragment頁面


3.實作TabListener後要orverride OnTabSelected

public class PaymentInfoActivity extends FragmentActivity implements
  TabListener {

 CollectionPagerAdapter mPagerAdapter;
 ViewPager mViewPager;

 @Override 
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_payment_info);

 final ActionBar mActionBar = getActionBar();
 mActionBar.setHomeButtonEnabled(true);
 mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
 mViewPager = (ViewPager) findViewById(R.id.pager);
 if (mViewPager != null) {
         mPagerAdapter = new CollectionPagerAdapter(
  getSupportFragmentManager());
  mViewPager.setAdapter(mPagerAdapter);
  mViewPager.setOnPageChangeListener(new ViewPager
                                        .SimpleOnPageChangeListener() {

     @Override
     public void onPageSelected(int position) {
  mActionBar.setSelectedNavigationItem(position);
     }
  });
 }
 TextView view1 = (TextView) getLayoutInflater().inflate(
   R.layout.view_custom_tab, null);
 view1.setText(mPagerAdapter.getPageTitle(0));
 mActionBar.addTab(mActionBar.newTab().setCustomView(view1)
   .setTabListener(this));
 TextView view2 = (TextView) getLayoutInflater().inflate(
   R.layout.view_custom_tab, null);
 view2.setText(mPagerAdapter.getPageTitle(1));
 mActionBar.addTab(mActionBar.newTab().setCustomView(view2)
   .setTabListener(this));
    }
}
  
 class CollectionPagerAdapter extends FragmentStatePagerAdapter {

  public CollectionPagerAdapter(FragmentManager fm) {
   super(fm);
  }

  @Override
  public Fragment getItem(int position) {
   switch (position) {
   case 0:
    return new PaymentPickupFragment();
   case 1:
    return new PaymentSearchFragment();
   }
   return null;
  }

   String[] title = new String[] {getResources().getString(R.string.web_payment),
     getResources().getString(R.string.search_payment) };

  @Override
  public CharSequence getPageTitle(int position) {

   return title[position];
  }

  @Override
  public int getCount() {
   // TODO Auto-generated method stub
   return 2;
  }

 }
 @Override
 public void onTabSelected(Tab tab, FragmentTransaction ft) {
  mViewPager.setCurrentItem(tab.getPosition());
 }


FragmentActivity的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" >

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</RelativeLayout>

最後要記得建立多個Fragment頁面加入Tab

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *