Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android利用Fragment實現Tab選項卡效果

Android利用Fragment實現Tab選項卡效果

編輯:關於Android編程

利用Fragment實現Tab選項卡效果: 

將RadioGroup與Fragment集合,實現tab選項卡效果,這裡面最關鍵的幾個文件: 

1.FragmentTabAdapter類:

/**
 *@Description: 
 *@Author:Nate Robinson 
 *@Since:2015-2-12
 */
public class FragmentTabAdapter implements RadioGroup.OnCheckedChangeListener
{
 private List<Fragment> fragments; // 一個tab頁面對應一個Fragment

 private RadioGroup rgs; // 用於切換tab

 private Activity activity; // Fragment所屬的Activity

 private int fragmentContentId; // Activity中所要被替換的區域的id

 private int currentTab; // 當前Tab頁面索引

 private OnRgsExtraCheckedChangedListener onRgsExtraCheckedChangedListener; // 用於讓調用者在切換tab時候增加新的功能

 public FragmentTabAdapter(Activity activity, List<Fragment> fragments, int fragmentContentId, RadioGroup rgs)
 {
  this.fragments = fragments;
  this.rgs = rgs;
  this.activity = activity;
  this.fragmentContentId = fragmentContentId;

  // 默認顯示第一頁
  android.app.FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
  ft.add(fragmentContentId, fragments.get(0));
  ft.commit();

  rgs.setOnCheckedChangeListener(this);

 }

 @Override
 public void onCheckedChanged(RadioGroup radioGroup, int checkedId)
 {
  for(int i = 0; i < rgs.getChildCount(); i++)
  {
   if(rgs.getChildAt(i).getId() == (checkedId))
   {
    Fragment fragment = fragments.get(i);
    FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
    getCurrentFragment().onPause(); // 暫停當前tab
    // getCurrentFragment().onStop(); // 暫停當前tab

    if(fragment.isAdded())
    {
     // fragment.onStart(); // 啟動目標tab的onStart()
     fragment.onResume(); // 啟動目標tab的onResume()
    }
    else
    {
     ft.add(fragmentContentId, fragment);
    }
    showTab(i); // 顯示目標tab
    ft.commit();

    // 如果設置了切換tab額外功能功能接口
    if(null != onRgsExtraCheckedChangedListener)
    {
     onRgsExtraCheckedChangedListener.OnRgsExtraCheckedChanged(radioGroup, checkedId, i);
    }

   }
  }

 }

 /**
  * 切換tab
  * @param idx
  */
 private void showTab(int idx)
 {
  for(int i = 0; i < fragments.size(); i++)
  {
   Fragment fragment = fragments.get(i);
   FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
   if(idx == i)
   {
    ft.show(fragment);
   }
   else
   {
    ft.hide(fragment);
   }
   ft.commit();
  }
  currentTab = idx; // 更新目標tab為當前tab
 }

 public int getCurrentTab()
 {
  return currentTab;
 }

 public Fragment getCurrentFragment()
 {
  return fragments.get(currentTab);
 }

 public OnRgsExtraCheckedChangedListener getOnRgsExtraCheckedChangedListener()
 {
  return onRgsExtraCheckedChangedListener;
 }

 public void setOnRgsExtraCheckedChangedListener(OnRgsExtraCheckedChangedListener onRgsExtraCheckedChangedListener)
 {
  this.onRgsExtraCheckedChangedListener = onRgsExtraCheckedChangedListener;
 }

 /**
  * 切換tab額外功能功能接口
  */
 public interface OnRgsExtraCheckedChangedListener
 {
  void OnRgsExtraCheckedChanged(RadioGroup radioGroup, int checkedId, int index);
 }
} 

2.activity_main.xml布局文件:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="@android:color/white"
 android:orientation="vertical" >

 <LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >

  <FrameLayout
   android:id="@+id/tab_content"
   android:layout_width="fill_parent"
   android:layout_height="0dp"
   android:layout_weight="1.0"
   android:background="#77557799" />

  <RadioGroup
   android:id="@+id/tabs_rg"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:gravity="center"
   android:orientation="horizontal"
   android:paddingBottom="7dp"
   android:paddingTop="7dp" >

   <RadioButton
    android:id="@+id/tab_rb_a"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1.0"
    android:background="@drawable/selector_tab"
    android:button="@null"
    android:checked="true"
    android:drawableTop="@drawable/tablatestalert"
    android:gravity="center"
    android:singleLine="true"
    android:text="Tab1"
    android:textColor="#000000"
    android:textSize="13sp" />

   <RadioButton
    android:id="@+id/tab_rb_b"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1.0"
    android:background="@drawable/selector_tab"
    android:button="@null"
    android:drawableTop="@drawable/tabsearch"
    android:gravity="center"
    android:singleLine="true"
    android:text="Tab2"
    android:textColor="#000000"
    android:textSize="13sp" />

   <RadioButton
    android:id="@+id/tab_rb_c"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1.0"
    android:background="@drawable/selector_tab"
    android:button="@null"
    android:drawableTop="@drawable/tabrecommd"
    android:gravity="center"
    android:singleLine="true"
    android:text="Tab3"
    android:textColor="#000000"
    android:textSize="13sp" />
  </RadioGroup>
 </LinearLayout>

</LinearLayout>

3.MainActivity類:

/**
 *@Description: 
 *@Author:Nate Robinson 
 *@Since:2015-2-12
 */
public class MainActivity extends Activity
{
 private RadioGroup rgs;

 private List<Fragment> fragments = new ArrayList<Fragment>();

 private int index;

 private static Boolean isExit = false;

 private static Boolean hasTask = false;

 private RadioButton button;

 private Timer tExit = new Timer();

 private TimerTask task = new TimerTask()
 {
  @Override
  public void run()
  {
   isExit = false;
   hasTask = true;
  }
 };

 private FragmentTabAdapter tabAdapter;

 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  fragments.add(new FragmentOne());
  fragments.add(new FragmentTwo());
  fragments.add(new FragmentThree());

  rgs = (RadioGroup) findViewById(R.id.tabs_rg);

  button = (RadioButton) findViewById(R.id.tab_rb_a);

  tabAdapter = new FragmentTabAdapter(this, fragments, R.id.tab_content, rgs);
  tabAdapter.setOnRgsExtraCheckedChangedListener(new FragmentTabAdapter.OnRgsExtraCheckedChangedListener()
  {
   @Override
   public void OnRgsExtraCheckedChanged(RadioGroup radioGroup, int checkedId, int index)
   {
    // 利用這個index可以實現,如果不是在主頁,按第一遍讓它先跳轉到第一個Fragment
    System.out.println("Extra---- " + index + " checked!!! ");
    MainActivity.this.index = index;
   }
  });
 }

 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event)
 {
  if(keyCode == KeyEvent.KEYCODE_BACK)
  {
   if(index == 0)
   {
    if(isExit == false)
    {
     isExit = true;
     Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
     if(!hasTask)
     {
      tExit.schedule(task, 1000);
     }
    }
    else
    {
     finish();
     System.exit(0);
    }
   }
   else
   {
    // 如果不是在主頁,按第一遍讓它先跳轉到第一個Fragment
    // 利用上面的check方法會導致onCheckedChanged方法被執行多次
    // rgs.check(button.getId());
    button.setChecked(true);
   }

  }
  return false;
 }
}

為了能同時學習Fragment生命周期,我在Fragment每個生命周期方法中加入了log打印,一個有三個這樣的Fragment,我只貼出其中一個代碼,其余和這個一樣:

/**
 *@Description: 
 *@Author:Nate Robinson 
 *@Since:2015-2-12
 */
public class FragmentOne extends BaseFragment
{

 private View view;
 

 @Override
 public void onAttach(Activity activity)
 {
  super.onAttach(activity);
  Log.d(TAG, "1==>FragmentOne=>onAttach");
 }

 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  Log.d(TAG, "2==>FragmentOne==>onCreate");
  super.onCreate(savedInstanceState);
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
 {
  Log.d(TAG, "3==>FragmentOne==>onCreateView");
  view = inflater.inflate(R.layout.fragment1, container, false);
  TextView tv = (TextView) view.findViewById(R.id.tv);
  tv.setText("FragmentOne");
  return view;
 }

 @Override
 public void onActivityCreated(Bundle savedInstanceState)
 {
  Log.d(TAG, "4==>FragmentOne==>onActivityCreated");
  super.onActivityCreated(savedInstanceState);
 }

 @Override
 public void onStart()
 {
  Log.d(TAG, "5==>FragmentOne==>onStart");
  super.onStart();
 }

 @Override
 public void onResume()
 {
  Log.d(TAG, "6==>FragmentOne==>onResume");
  super.onResume();
 }

 @Override
 public void onPause()
 {
  Log.d(TAG, "7==>FragmentOne==>onPause");
  super.onPause();
 }

 @Override
 public void onStop()
 {
  Log.d(TAG, "8==>FragmentOne==>onStop");
  super.onStop();
 }

 @Override
 public void onDestroyView()
 {
  Log.d(TAG, "9==>FragmentOne==>onDestroyView");
  super.onDestroyView();
 }

 @Override
 public void onDestroy()
 {
  Log.d(TAG, "10==>FragmentOne==>onDestroy");
  super.onDestroy();
 }

 @Override
 public void onDetach()
 {
  Log.d(TAG, "11==>FragmentOne==>onDetach");
  super.onDetach();
 }

 @Override
 public void onViewCreated(View view, Bundle savedInstanceState)
 {

  Log.d(TAG, "FragmentOne==>onViewCreated");
  super.onViewCreated(view, savedInstanceState);
 }
}

在編寫過程中,我為了實現如果不是在主頁,按第一遍讓它先跳轉到第一個Fragment這個效果,一開始使用了rgs.check(button.getId());這個方法,結果發現,這樣的話onCheckedChanged監聽事件會執行兩次,後來改為button.setChecked(true);這個方法之後,成功解決了這個問題。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved