Android ActionBar 初探
1.指南,例子,个人感觉
首先上官网指南链接http://developer.android.com/guide/topics/ui/actionbar.html
参考了官网上的例子http://developer.android.com/samples/ActionBarCompat-Basic/index.html
初看指南感觉ActionBar 的作用类似于web 开发中常用的include heder.html ,如cnblog 页面总第一行 。
2.兼容问题: sdk 11及11以上 可以直接使用,sdk 11以下则需要support-v7
PS:使用这两种在配置文件里也要区别如下 ,注意下面#后面是使用sdk 11自带的ActionBar 配置
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:support="http://schemas.android.com/apk/res-auto" # xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.example.actionbar.MainActivity" > <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="@string/action_settings" support:showAsAction="never" #app:showAsAction="never"/> <item android:id="@+id/menu_refresh" android:icon="@drawable/ic_action_refresh" android:title="@string/menu_refresh" support:showAsAction="ifRoom" />
3.构造方法
有配置文件,和程序代码里构建两种
@Override public boolean onCreateOptionsMenu(Menu menu) {
配置文件构建 getMenuInflater().inflate(R.menu.main, menu); MenuItem locationItem = menu.add(0,R.id.menu_location,0,R.string.menu_location);
程序构建 locationItem.setIcon(R.drawable.ic_action_location); MenuItemCompat.setShowAsAction(locationItem, MenuItem.SHOW_AS_ACTION_IF_ROOM); return true; }
4.全代码
package com.example.actionbar; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; //@SuppressLint("NewApi") public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sample_main); // android.app.ActionBar actionBar = getActionBar(); //actionBar.hide(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem locationItem = menu.add(0,R.id.menu_location,0,R.string.menu_location); locationItem.setIcon(R.drawable.ic_action_location); MenuItemCompat.setShowAsAction(locationItem, MenuItem.SHOW_AS_ACTION_IF_ROOM); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case R.id.menu_refresh: // Here we might start a background refresh task return true; case R.id.menu_location: // Here we might call LocationManager.requestLocationUpdates() return true; case R.id.menu_settings: // Here we would open up our settings activity return true; case R.id.action_settings: // Here we would open up our settings activity return true; } return super.onOptionsItemSelected(item); } }
5.后续.....