Android開發之Android Material Design Toolbar自訂隨筆,androidtoolbar

來源:互聯網
上載者:User

Android開發之Android Material Design Toolbar自訂隨筆,androidtoolbar

一、自訂Toolbar的menu:

在menu下建立menu.xml檔案,自訂menu的樣式:

 1 <menu xmlns:android="http://schemas.android.com/apk/res/android" 2     xmlns:app="http://schemas.android.com/apk/res-auto" 3     xmlns:tools="http://schemas.android.com/tools" 4     tools:context=".MainActivity"> 5     <item 6         android:id="@+id/action_search" 7         android:orderInCategory="80" 8         android:title="action_search" 9         app:showAsAction="ifRoom"10         android:icon="@drawable/search_ic_selector"/>11 </menu>

二、自訂Toolbar,Toolbar一般是共用:

建立common_toolbar.xml檔案:

 1 <?xml version="1.0" encoding="utf-8"?> 2 <android.support.v7.widget.Toolbar 3     xmlns:android="http://schemas.android.com/apk/res/android" 4     xmlns:app="http://schemas.android.com/apk/res-auto" 5     android:id="@+id/common_toolbar_top" 6     android:layout_width="match_parent" 7     android:layout_height="wrap_content" 8     android:background="@color/colorPrimary" 9     android:minHeight="?attr/actionBarSize"10     app:popupTheme="@style/ThemeOverlay.AppCompat.Light"11     app:navigationIcon="?attr/homeAsUpIndicator"12     app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"13    >14 </android.support.v7.widget.Toolbar>

註:其中app:navigationIcon="?attr/homeAsUpIndicator"用於設定返回表徵圖

三、在布局檔案中引入自訂的Toolbar:

<include    layout="@layout/common_toolbar"></include>

四、activity中聲明Toolbar以及對menu的事件監聽:

註:Activity必須繼承AppCompatActivity

1、聲明Toolbar:

1 Toolbar toolbar = (Toolbar) findViewById(R.id.common_toolbar_top);2 setSupportActionBar(toolbar);

2、Toolbar設定標題等:

setTitle(R.string.fragment_for_why_title);

3、對menu進行聲明和事件監聽:

menu聲明:

@Overridepublic boolean onCreateOptionsMenu(Menu menu) {    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.main, menu);    return true;}

事件監聽:

@Overridepublic boolean onOptionsItemSelected(MenuItem item) {    int id = item.getItemId();    //noinspection SimplifiableIfStatement    if (id == R.id.action_search) {              return true;    }    return super.onOptionsItemSelected(item);}

五、最終:

                      

Demo:http://shouji.baidu.com/software/item?docid=8118536&from=as

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.