接著上一篇Action Bar 加入Back返回鍵, 在Action Bar中加入自定義View. 依然先看效果:
actionbar自定義view的布局文件action_bar.xml, 此處可以任意發揮, 實現腦海中的自定義View.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/action_bar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#EEA9B8"
android:text="@string/action_bar_title" />
<Spinner
android:id="@+id/action_bar_spinner"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
</Spinner>
</LinearLayout>
上邊的自定義View裡面我用了個Spinner, 那Spinner的Item的布局, 借用了之前抽屜導航Item的布局drawer_item.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?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:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:id="@+id/drawer_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/drawer_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
布局准備好了, 接下來就是在Activity裡面寫一些.
首先是onCreate()方法裡面准備一下.
1 2 3 4 5 6 7 8 9 10 11 12
/** action_bar添加自定義view */
View actionbarLayout = LayoutInflater.from(this).inflate(R.layout.action_bar, null);
mActionbarSpinne = (Spinner) actionbarLayout.findViewById(R.id.action_bar_spinner);
//setAdapter可以根據具體情況, 此處不必深究.
mActionbarSpinne.setAdapter(new SimpleAdapter(this,
getDrawerItems(true), R.layout.drawer_item, new String[] {
"drawer_img", "drawer_title" }, new int[] {
R.id.drawer_img, R.id.drawer_title }));
mActionbarSpinne.setOnItemSelectedListener(new SpinnerItemSelectedListener());
//使自定義的普通View能在title欄顯示, actionBar.setCustomView能起作用.
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(actionbarLayout);
然後Spinner Item選中時, 加個Listener
1 2 3 4 5 6 7 8 9 10 11 12/**
* 監聽action_bar的spinner item選擇事件
*/
private class SpinnerItemSelectedListener implements OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position,
long arg3) {
selectItem(view, position, MESSAGE_SPINNER_ITEM);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {}
}
Listener的selectItem()細節如下
1 2 3 4 5 6 7
if (messageId == MESSAGE_SPINNER_ITEM) {
if (position != 0) {
TextView title = (TextView) view.findViewById(R.id.drawer_title);
String cityName = title.getText().toString();
this.cityInput.setText(cityName);
}
}
至此, 可以根據具體情況在Action bar上面自定義View
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11