Android中ActionBar的使用
1,什么是ActionBar?
3.0以上可以直接使用
2.1以上3.0一下,需要依托jar包
这里只讨论3.0以上的使用方法:
<manifest ... >
<uses-sdk android:minSdkVersion="11" ... />
...
</manifest>
Theme必须是Theme.Holo或者其子类
Menu文件夹下
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
android:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="@+id/action_settings"
android:title="@string/action_settings"
android:showAsAction="never" />
</menu>
在Activity中覆写这两个方法
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
就会出现上述效果,其实你会发现,这跟添加menu菜单项的方法是一样的
为什么定义了两个item,一个在上面,一个点击menu才能出现呢?这跟她里面的一个属性有关
android:showAsAction="ifRoom"
2,另一中用途,不管在哪个Activity页面,只要点击下面的标示,就会返回主Activity
步骤:
<application ... >
...
<!-- The main/home activity (it has no parent activity) -->
<activity
//这个是主Activity,要实现上面所述效果,其他Activity需要指定其父Activity是这个Activity
android:name="com.example.myfirstapp.MainActivity" ...>
...
</activity>
<!-- A child of the main activity -->
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
在其他Activity中的onCreate方法中:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_displaymessage);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// If your minSdkVersion is 11 or higher, instead use:
API是11或者更高的,调用下面方法
getActionBar().setDisplayHomeAsUpEnabled(true);
}