android L引入的一個新控件android 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
<style name="AppTheme.Base" parent="Theme.AppCompat"> <item name="windowActionBar">false</item> <item name="android:windowNoTitle">true</item> </style>
然后在xml中:
<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:
@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。
@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編譯還沒成功過,今后會介紹更多的相關文章。