Android应用开发中Action bar编写的入门教程
从Android 3.0开始除了我们重点讲解的Fragment外,Action Bar也是一个重要的内容,Action Bar主要是用于代替传统的标题栏,对于Android平板设备来说屏幕更大它的标题使用Action Bar来设计可以展示更多丰富的内容,方便操控。
Action Bar主要功能包含:
1. 显示选项菜单
2. 提供标签页的切换方式的导航功能,可以切换多个fragment.
3. 提供下拉的导航条目.
4. 提供交互式活动视图代替选项条目
5. 使用程序的图标作为返回Home主屏或向上的导航操作。
提示在你的程序中应用ActionBar需要注意几点,SDK和最终运行的固件必须是Android 3.0即honeycomb,在androidmanifest.xml文件中的uses-sdk元素中加入android:minSdkVersion 或android:targetSdkVersion,类似
< manifest xmlns:android="http://schemas.android.com/apk/res/android" package="eoe.android.cwj" android:versionCode="1" android:versionName="1.0"> < uses-sdk android:minSdkVersion="honeycomb" /> < application ... > < /application> < /manifest>
如果需要隐藏Action Bar可以在你的Activity的属性中设置主题风格为NoTitleBar在你的manifest文件中,下面的代码在3.0以前是隐藏标题,而在3.0以后就是隐藏ActionBar了,代码为:
< activity android:theme="@android:style/Theme.NoTitleBar">
一、添加活动条目 Action Items
对于活动条目大家可以在下图看到Android 3.0的标题右部分可以变成工具栏,下面的Save和Delete就是两个Action Items活动条目。
下面是一个menu的layout布局文件代码
< ?xml version="1.0" encoding="utf-8"?> < menu xmlns:android="http://schemas.android.com/apk/res/android"> < item android:id="@+id/menu_add" android:icon="@drawable/ic_menu_save" android:title="@string/menu_save" android:showAsAction="ifRoom|withText" /> < /menu>
而其他代码类似Activity中的Menu,比如
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // 当Action Bar的图标被单击时执行下面的Intent Intent intent = new Intent(this, Android123.class); startActivity(intent); break; } return super.onOptionsItemSelected(item); }
对于ActionBar的创建,可以在你的Activity中重写onStart方法:
@Override protected void onStart() { super.onStart(); ActionBar actionBar = this.getActionBar(); actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_HOME_AS_UP); }
调用getActionBar方式在你的Activity的onCreate中时需要注意必须在调用了setContentView之后。
二、添加活动视图 Action View
对于ActionView,我们可以在menu的布局文件使用中来自定义searchview布局,如下:
< item android:id="@+id/menu_search" android:title="Search" android:icon="@drawable/ic_menu_search" android:showAsAction="ifRoom" android:actionLayout="@layout/searchview" />
也可以直接指定Android系统中的SearchView控件,那么这时menu"_search的代码要这样写:
< item android:id="@+id/menu_search" android:title="Search" android:icon="@drawable/ic_menu_search" android:showAsAction="ifRoom" android:actionViewClass="android.widget.SearchView" />
大家注意上面的两种方法中一个属性是actionLayout制定一个layout xml布局文件,一个是actionViewClass指定一个类,最终调用可以在Activity中响应onCreateOptionsMenu方法映射这个menu布局即可.
@Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.options, menu); SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); return super.onCreateOptionsMenu(menu); }
三、添加标签 Tabs
在ActionBar中实现标签页可以实现android.app.ActionBar.TabListener ,重写onTabSelected、onTabUnselected和onTabReselected方法来关联Fragment。代码如下:
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中,代码如下;
@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,最终改进后的代码为
ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setListNavigationCallbacks(mSpinnerAdapter, mNavigationCallback);
上面我们通过setListNavigationCallbacks方法绑定一个SpinnerAdapter控件,具体的OnNavigationListener代码示例为;
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的代码为:
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; } }
五、实现切换Tabs标签;
Activity代码:
public class ActionBarTabs extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.action_bar_tabs); } public void onAddTab(View v) { final ActionBar bar = getActionBar(); final int tabCount = bar.getTabCount(); final String text = "Tab " + tabCount; bar.addTab(bar.newTab().setText(text) .setTabListener(new TabListener(new TabContentFragment(text)))); } public void onRemoveTab(View v) { final ActionBar bar = getActionBar(); bar.removeTabAt(bar.getTabCount() - 1); } public void onToggleTabs(View v) { final ActionBar bar = getActionBar(); if (bar.getNavigationMode() == ActionBar.NAVIGATION_MODE_TABS) { bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE); } else { bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE); } } public void onRemoveAllTabs(View v) { getActionBar().removeAllTabs(); } private class TabListener implements ActionBar.TabListener { private TabContentFragment mFragment; public TabListener(TabContentFragment fragment) { mFragment = fragment; } public void onTabSelected(Tab tab, FragmentTransaction ft) { ft.add(R.id.fragment_content, mFragment, mFragment.getText()); } public void onTabUnselected(Tab tab, FragmentTransaction ft) { ft.remove(mFragment); } public void onTabReselected(Tab tab, FragmentTransaction ft) { Toast.makeText(ActionBarTabs.this, "Reselected!", Toast.LENGTH_SHORT).show(); } } private class TabContentFragment extends Fragment { private String mText; public TabContentFragment(String text) { mText = text; } public String getText() { return mText; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View fragView = inflater.inflate(R.layout.action_bar_tab_content, container, false); TextView text = (TextView) fragView.findViewById(R.id.text); text.setText(mText); return fragView; } } }
涉及的布局文件action_bar_tabs.xml代码为:
< ?xml version="1.0" encoding="utf-8"?> < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> < FrameLayout android:id="@+id/fragment_content" android:layout_width="match_parent" android:layout_height="0dip" android:layout_weight="1" /> < LinearLayout android:layout_width="match_parent" android:layout_height="0dip" android:layout_weight="1" android:orientation="vertical"> < Button android:id="@+id/btn_add_tab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_add_tab" android:onClick="onAddTab" /> < Button android:id="@+id/btn_remove_tab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_remove_tab" android:onClick="onRemoveTab" /> < Button android:id="@+id/btn_toggle_tabs" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_toggle_tabs" android:onClick="onToggleTabs" /> < Button android:id="@+id/btn_remove_all_tabs" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_remove_all_tabs" android:onClick="onRemoveAllTabs" /> < /LinearLayout> < /LinearLayout>
布局文件action_bar_tab_content.xml;
< ?xml version="1.0" encoding="utf-8"?> < TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" />

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

OnePlus'sister brand iQOO has a 2023-4 product cycle that might be nearlyover; nevertheless, the brand has declared that it is not done with itsZ9series just yet. Its final, and possibly highest-end,Turbo+variant has just beenannouncedas predicted. T
