Training-ActionBar
阅读:http://developer.android.com/training/basics/actionbar/index.html
对于API11以下的兼容:
- Update your activity so that it extends
ActionBarActivity
. For example:public class Main Activit yextends ActionBarActivity{...}- In your manifest file, update either the
<application>
element or individual<activity>
elements to use one of theTheme.AppCompat
themes. For example:<activityandroid:theme="@style/Theme.AppCompat.Light" ... >Note: If you've created a custom theme, be sure it uses one of the
Theme.AppCompat
themes as its parent. For details, see Styling the Action Bar.
首先,需要定义一个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>
接下来覆盖两个方法:
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); } }
使得按钮出现并有所响应。
The Up button in Gmail.
首先定义父Activity
<application ... > ... <!-- The main/home activity (it has no parent 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>
接下来代码里呈现:
@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: // getActionBar().setDisplayHomeAsUpEnabled(true); }
关于样式的配置,http://developer.android.com/training/basics/actionbar/styling.html 有详细的介绍。
关于ActionBar覆盖在内容上面的,可看:http://developer.android.com/training/basics/actionbar/overlaying.html