Toolbar的使用以及自定义Toolbar的方法

来源:互联网 发布:机器聊天软件 编辑:程序博客网 时间:2024/04/24 05:24

android5.0以后出现了Toolbar,今天折腾了一下,在此做个记录方便以后查看,同时也给有需要的朋友们参考!!!!!很惭愧只做了一点微小的工作。

下面将完成两个方面的工作:

一、ToolBar的基本使用,如下是效果图:


二、自定义ToolBar,如下是效果图:

一、Toolbar的基本使用

1、新建工程后在activity_main.xml布局中添加如下代码:

<?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:fitsSystemWindows="true"    tools:context="com.gta.yanwen.hellotoolbar.MainActivity">    <android.support.design.widget.AppBarLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:theme="@style/AppTheme.AppBarOverlay">        <android.support.v7.widget.Toolbar            android:id="@+id/toolbar"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:background="?attr/colorAccent"            app:navigationIcon="@mipmap/left_arrow_icon"            app:logo="@mipmap/ic_launcher"            app:title="Title"            app:subtitle="SubTitle"            />    </android.support.design.widget.AppBarLayout></android.support.design.widget.CoordinatorLayout>
这是个主布局,根布局我们先不管,也可用RelativeLayout,主要看看AppBarLayout和Toolbar这两个view,AppBarLayout定义Toolbar所在的布局,设置了android:theme属性,这个属性是设置Toolbar的主题,主要是文字和背景等一些属性的集合,若不设置theme这个属性也可以通过?attr/color设置某个部位的单独属性。

AppBarLayout布局里面包含了ToolBar这个布局,来一个个分析她的属性:

android:background      设置toolbar的背景颜色

android:navigationIcon  设置toolbar最左边的按钮图标

app:logo                       设置Logo图标

app:title       设置Title标题

app:subtitle      设置副标题SubTitle

当然还有标题字体颜色、副标题字体颜色,读者可以自行去尝试。

注意:?attr/colorAccent属性值在style文件中有定义。

2、主布局设置完了以后再编写MainActivity.java文件,贴出代码如下慢慢分析:

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        toolbar.inflateMenu(R.menu.menu_main);        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {            @Override            public boolean onMenuItemClick(MenuItem item) {                int id = item.getItemId();                if (id == R.id.action_settings) {                    Toast.makeText(MainActivity.this, "action_menu", Toast.LENGTH_SHORT).show();                }                return true;            }        });    }}
代码部分也很简单,获取到toolbar的id,设置了menu选项菜单,并设置了选项菜单每一项的点击监听事件。

到此编译、运行可出现图一效果。

二、自定义Toolbar

思路:编写CurToolbar类继承Toolbar,左边箭头和上面使用方法一样,邮编部分加了一个TextView和ImageButton。

1、在layout下新建tool_bar_layout.xml布局文件,如下:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:id="@+id/toolbar_search_view"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginRight="50dp"        android:padding="5dp"        android:drawableLeft="@mipmap/search_icon"        android:singleLine="true"        android:duplicateParentState="true"        android:clickable="true"        android:layout_centerVertical="true"        android:gravity="center_vertical"        android:background="@drawable/bg_toolbar_search_view"        android:hint="输入需要搜索的商品名"/>    <ImageButton        android:id="@+id/toolbar_imgbtn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginRight="10dp"        android:layout_centerVertical="true"        android:layout_alignParentRight="true"        android:background="@android:color/transparent"/>    </RelativeLayout>
在RelativeLayout中放置了两个控件,分别是TextView和ImageButton,TextView是点击搜索控件,其中加载了bg_toolbar_search_view样式(后面将贴出)。布局的最右边放置一个带加号图片等ImageButton,这个布局是自定义Toolbar的主要部分。

2、其次新建CurToolbar继承Toolbar,代码如下:

public class CurToolBar extends Toolbar {    private ImageView mImageView;    private TextView mSearchEdit;    private View view;    public CurToolBar(Context context) {        this(context, null);    }    public CurToolBar(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public CurToolBar(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        view = LayoutInflater.from(getContext()).inflate(R.layout.tool_bar_layout, null);ViewById(R.id.toolbar_title);        mImageView = (ImageView) view.findViewById(R.id.toolbar_imgbtn);        mSearchEdit = (TextView) view.findViewById(R.id.toolbar_search_view);        if (mImageView != null) {            final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs,                    R.styleable.CurToolBar, defStyleAttr, 0);            mImageView.setImageDrawable(a.getDrawable(R.styleable.CurToolBar_rightButtonIcon));            a.recycle();        }        if (mSearchEdit != null) {            final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs,                    R.styleable.CurToolBar, defStyleAttr, 0);            boolean isVisible = a.getBoolean(R.styleable.CurToolBar_isShowSearchView, false);            mSearchEdit.setVisibility(isVisible ? View.VISIBLE : View.GONE);            a.recycle();        }        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER_HORIZONTAL);        addView(view, lp);    }}
通过LayoutInflater获取tool_bar_layout布局,随后获取到里面的TextView和ImageButton,调用TintTypeArray.obtainStyledAttributes()获取到自定义的CurToolbar属性集合,然后获取到其中的rightButtonIcon和isShowSearchView这两个自定义的属性值,最后调用addView()将tool_bar_layout布局添加到Toolbar中。

3、在values下新建attrs文件,编写如下属性:

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="CurToolBar" >        <attr name="rightButtonIcon" format="reference"/>        <attr name="isShowSearchView" format="boolean"/>    </declare-styleable></resources>
rightButtonIcon属性,值类型是reference

isShowSearchView属性,值类型是boolean

4、再编写activity_main.xml主布局,如下:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:fitsSystemWindows="true"    tools:context="com.gta.yanwen.hellotoolbar.MainActivity">    <android.support.design.widget.AppBarLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:theme="@style/AppTheme.AppBarOverlay">        <com.gta.yanwen.hellotoolbar.CurToolBar            android:id="@+id/toolbar"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:minHeight="?attr/actionBarSize"            android:background="?attr/colorAccent"            app:navigationIcon="@mipmap/left_arrow_icon"            app:rightButtonIcon="@mipmap/plus_icon"            app:isShowSearchView="true"></com.gta.yanwen.hellotoolbar.CurToolBar>    </android.support.design.widget.AppBarLayout></android.support.design.widget.CoordinatorLayout>
在AppBarLayout中加入CurToolBar自定义的布局,仔细看会发现加入了我们刚刚自定义的rightButtonIcon和isShowSearchIcon属性,当程序运行是CurToolBar类中会读到这两个属性的值并进行设置。

5、最后编写MainActivity.java,如下:

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        toolbar.findViewById(R.id.toolbar_imgbtn).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Toast.makeText(MainActivity.this, "ToolBar ImageButton", Toast.LENGTH_SHORT).show();            }        });        toolbar.findViewById(R.id.toolbar_search_view).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {//                Toast.makeText(MainActivity.this, "Toolbar Search Edittext", Toast.LENGTH_SHORT).show();                startActivity(new Intent(MainActivity.this, SearchCommodityActivity.class));            }        });        toolbar.setNavigationOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Toast.makeText(MainActivity.this, "onNavigationOnClick", Toast.LENGTH_SHORT).show();            }        });    }}
这里主要是设置了CurToolbar中控件的点击监听事件,在SearchView这个TextView时启动了SearchCommodityActivity搜索界面,贴出如下:

SearchCommodityActivity.class

public class SearchCommodityActivity extends Activity {    private ImageButton back_btn;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.search_commondity_layout);        back_btn = (ImageButton) findViewById(R.id.back_btn);        back_btn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                SearchCommodityActivity.this.finish();            }        });    }}
search_commodity_layout.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="#EDECEC">    <ImageButton        android:id="@+id/back_btn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@mipmap/left_arrow_icon"/>    <EditText        android:layout_width="match_parent"        android:layout_height="match_parent"        android:gravity="center_vertical"        android:paddingLeft="15dp"        android:layout_marginRight="20dp"        android:background="@mipmap/bg_edit_ware"        android:focusable="true"        android:focusableInTouchMode="true"/></LinearLayout>
6、编译、运行程序可出现如上图二所示效果

源代码下载链接:

1 0