zoukankan      html  css  js  c++  java
  • Android开发之Android Material Design Toolbar自定义随笔

    一、自定义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声明:

    @Override
    public 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;
    }

    事件监听:

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

    五、最终效果图:

    Toolbar自定义                      Toolbar自定义

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

     

     

  • 相关阅读:
    10个最佳jQuery Lightbox效果插件收集
    JavaScript 中的内存泄露模式
    推荐6 款免费的图标编辑器
    Google 排名中的 10 个最著名的 JavaScript 库
    影响搜索引擎排名的因素2009年(总览)
    2009 年度最佳 jQuery 插件
    使用 Nginx 提升网站访问速度
    10个新的最有前途的JavaScript框架
    IE8面向Web开发人员的功能改进
    IE6, IE7, IE8 CSS 兼容速查表
  • 原文地址:https://www.cnblogs.com/android-blogs/p/4975118.html
Copyright © 2011-2022 走看看