android support v7 Toolbar控件

Toolbar是android L引入的一個新控件,可以理解爲action bar的第二代:提供了action bar類似的功能,但是更靈活。不像actionbar那麼固定,Toolbar更像是一般的View元素,可以被放置在view樹體系的任意位置,可以應用動畫,可以跟着scrollView滾動,可以與佈局中的其他view交互。當然,你還可以用Toolbar替換掉actionbar,只需調用 Activity.setActionBar()。

爲了兼容更多的設備一般我們都是通過AppCompat 中的 android.support.v7.widget.Toolbar來使用Toolbar。

在這個例子中Toolbar擴展了更高的高度,同時被一個內容區域覆蓋了一部分


有兩種使用Toolbar的方式:

  • Use a Toolbar as an Action Bar when you want to use the existing Action Bar facilities (such as menu inflation and selection, ActionBarDrawerToggle, and so on) but want to have more control over its appearance.

  • Use a standalone Toolbar when you want to use the pattern in your app for situations that an Action Bar would not support; for example, showing multiple toolbars on the screen, spanning only part of the width, and so on.


(1)將Toolbar當作actionbar來使用。這種情況一般發生在你想利用actionbar現有的一些功能(比如能夠顯示菜單中的操作項,響應菜單點擊事件,使用ActionBarDrawerToggle等),但是又想獲得比actionbar更多的控制權限。

(2)將Toolbar當作一個獨立的控件來使用,這種方式又名Standalone

Action Bar

如果你要將Toolbar當作actionbar來使用,你首先要去掉actionbar,最簡單的方法是使用Theme.AppCompat.NoActionBar主題。

或者是設置主題的屬性android:windowNoTitle爲true

1
2
3
4
<style name="AppTheme.Base" parent="Theme.AppCompat">
  <item name="windowActionBar">false</item>
  <item name="android:windowNoTitle">true</item>
</style>

然後在xml中:

1
2
3
4
5
6
<android.support.v7.widget.Toolbar
    android:id=”@+id/my_awesome_toolbar”
    android:layout_height=”wrap_content”
    android:layout_width=”match_parent”
    android:minHeight=”?attr/actionBarSize”
    android:background=”?attr/colorPrimary” />

Toolbar的高度、寬度、背景顏色等等一切View的屬性完全取決於你,這都是因爲Toolbar本質上只是個ViewGroup。然後在activity或者Fragment中將Toolbar設置成actionbar:

1
2
3
4
5
6
7
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blah);
    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);
}

至此,所有的menu菜單元素都會顯示在你的Toolbar上,並且響應標準的菜單回調。

Standalone

將Toolbar當作一個獨立的控件來使用是不需要去掉actionbar的(兩者可以共存),可以使用任意主題。但是在這種情況下,menu菜單並不會自動的顯示在Toolbar上,Toolbar也不會響應菜單的回調函數,如果你想讓menu菜單項顯示在Toolbar上,必須手動inflate menu。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blah);
    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    // Set an OnMenuItemClickListener to handle menu item clicks
    toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            // Handle the menu item
            return true;
        }
    });
    // Inflate a menu to be displayed in the toolbar
    toolbar.inflateMenu(R.menu.your_toolbar_menu);
}

因爲Toolbar是新的控件,我所知道的也只有這麼多,android l編譯還沒成功過,今後會介紹更多的相關文章。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章