Android系統中ActionBar默認的佈局不美觀且難於控制,經過爲ActionBar自定義佈局的方式能夠靈活控制ActionBar。 android
效果: eclipse
android集成開發環境eclipse、ADT ide
android sdk 3.0及以上 工具
自定義Activity主題和ActionBar樣式 佈局
在新建的android工程的res/values/styles.xml添加自定義ActionBar樣式的代碼和自定義Activity主題的代 碼,並在AndroidMainfest.xml中給須要使用該自定義ActionBar的Activity中加入該主題: this
(1)自定義ActionBar樣式代碼以下: spa
<!-- 自定義ActionBar -->
<style name="me_action_bar"
parent="@android :style/Widget.Holo.Light.ActionBar">
<!-- 更改ActionBar背景 -->
<item name="android:background">#5FBDCB</item>
</style> .net
(2)自定義Activity主題代碼以下: xml
<!-- 自定義Activity主題 窗口樣式 -->
<style name="ActivityTheme_Light"
parent="android:Theme.Holo.Light">
<item name="android:actionBarStyle">@style/me_action_bar</item>
</style> ip
(3)在AndroidManifest.xml文件中須要使用該自定義ActionBar的Activity中加入該主題以下:
<activity
android:theme="@style/ActivityTheme_Light"
android:name="com.looookme.actionbardemo.SecondActivity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
在Activity中加載ActionBar的自定義佈局
(1)ActionBar加載自定義佈局的代碼封裝以下:
private void setActionBarLayout(int layoutId) {
// TODO Auto-generated method stub
ActionBar actionBar = getActionBar();
if(null != actionBar){
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(layoutId, null);
ActionBar.LayoutParams lParams = new ActionBar.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
actionBar.setCustomView(v, lParams);
}
}
(2)在onCreate()方法中調用該方法,並傳入自定義的佈局文件ID:
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setActionBarLayout(R.layout.actionbar_layout);
}
(3)自定義佈局文件「actionbar_port_layout.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="44dp" android:orientation="horizontal" android:gravity="center_vertical" android:background="#008000"> <ImageView android:layout_marginLeft="24dp" android:layout_width="36dp" android:layout_height="36dp" android:src="@drawable/ic_launcher"/> <EditText android:layout_marginLeft="24dp" android:layout_weight="1" android:layout_width="0dp" android:layout_height="36dp" android:hint="Please input " android:id="@+id/et_input"/> <ImageButton android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:layout_width="30dp" android:layout_height="30dp" android:src="@drawable/action_search"/> </LinearLayout>