上一節所講內容為ActionBar概述與創建,本節主要講解ActionBar如何添加Tabs標簽和下拉導航。
一、添加標簽 Tabs
在ActionBar中實現標簽頁可以實現android.app.ActionBar.TabListener ,重寫onTabSelected、onTabUnselected和onTabReselected方法來關聯Fragment。代碼如下:
Java代碼
- private class MyTabListener implements ActionBar.TabListener {
- private TabContentFragment mFragment;
- public TabListener(TabContentFragment fragment) {
- mFragment = fragment;
- } @Override
- public void onTabSelected(Tab tab, FragmentTransaction ft) {
- ft.add(R.id.fragment_content, mFragment, null);
- }
- @Override
- public void onTabUnselected(Tab tab, FragmentTransaction ft) {
- ft.remove(mFragment);
- }
- @Override
- public void onTabReselected(Tab tab, FragmentTransaction ft) {
- }
-
- }
接下來我們創建ActionBar在Activity中,代碼如下:
Java代碼
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- final ActionBar actionBar = getActionBar(); //提示getActionBar方法一定在setContentView後面
- actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
- actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
- Fragment artistsFragment = new ArtistsFragment();
- actionBar.addTab(actionBar.newTab().setText(R.string.tab_artists).setTabListener(new TabListener(artistsFragment)));
- Fragment albumsFragment = new AlbumsFragment();
- actionBar.addTab(actionBar.newTab().setText(R.string.tab_albums).setTabListener(new TabListener(albumsFragment)));
- }
二、添加下拉導航 Drop-down Navigation
創建一個SpinnerAdapter提供下拉選項,和Tab方式不同的是Drop-down只需要修改下setNavigationMode的模式,將ActionBar.NAVIGATION_MODE_TABS改為ActionBar.NAVIGATION_MODE_LIST,最終改進後的代碼為:
Java代碼
- ActionBar actionBar = getActionBar();
- actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
- actionBar.setListNavigationCallbacks(mSpinnerAdapter, mNavigationCallback);
上面我們通過setListNavigationCallbacks方法綁定一個SpinnerAdapter控件,具體的OnNavigationListener代碼示例為:
Java代碼
- mOnNavigationListener = new OnNavigationListener() {
- String[] strings = getResources().getStringArray(R.array.action_list);
- @Override
- public boolean onNavigationItemSelected(int position, long itemId) {
- ListContentFragment newFragment = new ListContentFragment();
- FragmentTransaction ft = openFragmentTransaction();
- ft.replace(R.id.fragment_container, newFragment, strings[position]);
- ft.commit();
- return true;
- }
-
- };
而其中的ListContentFragment的代碼為:
Java代碼
- public class ListContentFragment extends Fragment {
- private String mText;
-
- @Override
- public void onAttach(Activity activity) {
- super.onAttach(activity);
- mText = getTag();
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- TextView text = new TextView(getActivity());
- text.setText(mText);
- return text;
- }
- }