Toolbar工具欄是谷歌推薦使用的工具欄(相對於ActionBar)。因爲它屬於Material控件,具有更好的靈活性。本記錄是從《第一行代碼andriod》中學習到的。應該不屬性原創。但考慮到一是並非直接轉載,另外 也加了一些自己的東西。姑且爲原創吧。
使用Toolbar總共需要五步。操作如下:
1.停用原來自動生成的ActionBar控件.
2.準備Menu菜單的xml文件和在相關活動頁中鑲入Toolbar控件。
3.在活動頁中填充Toolbar控件。
4.填充自定義菜單和設置相關事件。
詳細操作如下:
1.首先要把原來屬於的ActionBar停止掉。在文件AndroidManifest.xml中引用了原來菜單的主題.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="ListView操作">
</activity>
<activity android:name=".ToolBarActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="com.example.myapp.ToolBarActivity" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
注意AppTheme來源於文件夾\src\main\res\value\style.xml之中。
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
將AppTheme的parent改成Theme.AppCompat.Light.NoActionBar。這樣原來的ActionBar 就被停用掉了。接下來我們當然要把自己的Toolbar放入到活動頁中啦。
2.準備一個要自己的Toolbar樣式文件 。
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:title="編輯"
android:icon="@mipmap/mango"
android:id="@+id/edit"
app:showAsAction="always"/>
<item android:title="保存"
android:icon="@mipmap/pear"
android:id="@+id/save"
android:menuCategory="alternative"
app:showAsAction="always"/>
</menu>
3.在活動頁的layout中放入一個Toolbar控件。
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
4.將Toolbar控件放入活動頁中。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tool_bar);
Toolbar toolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
}
5.把自定義的Menu內容放入Toolbar之中.並指定相關事件處理。
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.edit:
Toast.makeText(this,"選擇了編輯菜單",Toast.LENGTH_SHORT).show();
break;
case R.id.save:
Toast.makeText(this,"選擇了保存",Toast.LENGTH_SHORT).show();
break;
}
return true;
}