自定义 ToolBar 实现标题栏

一 、自定义ToolBar前 ,先贴一下style ,相信大家一定和我一样感到既陌生又熟悉

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorAccent</item> <!--actionbar 背景颜色-->
        <item name="colorPrimaryDark">@color/colorAccent</item><!--状态栏颜色-->
        <item name="colorAccent">@color/colorAccent</item><!--各控制元件(如:check box、switch 或是 radoi) 被勾选 (checked) 或是选定 (selected) 的颜色。-->
        <item name="android:textColorPrimary">#fff</item><!--action 标题文字颜色-->
        <item name="android:windowBackground">@color/white</item><!--Window color-->
        <!--去掉标题-->
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="colorControlNormal">@color/white</item><!--各控制元件的预设颜色。-->

        <item name="android:navigationBarColor">@color/colorPrimary</item>
    </style>

    <!-- 控制 toolbar 绑定的 menu的风格-->
    <style name="ToolbarPopupTheme" parent="@style/ThemeOverlay.AppCompat.Dark">
        <item name="android:colorBackground">@color/colorPrimary</item>
        <item name="android:textColor">@android:color/holo_green_light</item>
        <item name="actionOverflowMenuStyle">@style/OverflowMenuStyle</item> <!--新增一个item,用于控制menu-->
        <item name="android:textSize">22sp</item>
    </style>

    <style name="OverflowMenuStyle" parent="Widget.AppCompat.Light.PopupMenu.Overflow">
        <item name="overlapAnchor">false</item>  <!--把该属性改为false即可使menu位置位于toolbar之下-->
    </style>


二、接下来,开始自定义ToolBar,主要满足两个功能 1、居中标题、左右两个ImageButton  2、带searchView 的Toolbar  听起来很简单,主要是复习一下组合式的自定义控件

下面直接贴源码

2.1、

/**
 * Created by 蔡宇奎 on 2017-3-17.
 */

public class MyToolBar extends Toolbar implements TextWatcher {
    private EditText toolbar_editText;
    private TextView toolbar_search;
    private TextView toolbar_textView;
    private ImageButton toolbar_imgBtn;
    private ImageButton toolbar_LeftimgBtn;
    private MyToolBarBtnListenter btnListenter;
    private MyToolBarEditTextListener editTextListener;

    public MyToolBar(Context context) {
        this(context, null);
    }

    public MyToolBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, android.support.v7.appcompat.R.attr.toolbarStyle);
    }

    public MyToolBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
//        setContentInsetsRelative(100,100);

        final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs,
                R.styleable.MyToolBar, defStyleAttr, 0);
        Drawable drawableRight = a.getDrawable(R.styleable.MyToolBar_RightImgButtonIcon);
        Drawable drawableLeft = a.getDrawable(R.styleable.MyToolBar_LeftImgButtonIcon);
        boolean aBoolean = a.getBoolean(R.styleable.MyToolBar_isShowEditText, false);
        String hint = a.getString(R.styleable.MyToolBar_editHint);
        if(!TextUtils.isEmpty(hint)){
            toolbar_editText.setHint(hint);
        }
        if (drawableRight != null) {
            setRightImageBtnDrawable(drawableRight);
        }
        if (drawableLeft != null) {
            setLeftImageBtnDrawable(drawableLeft);
        }

        /**
         * 如果显示editText为true,则把editText 设为显示,TextView设为隐藏
         */
        if (aBoolean) {
            showEditText();
            hintTextView();
        } else {
            hintEditText();
        }

    }


    private void initView() {
        View view = View.inflate(getContext(), R.layout.mytoolbar_layout, null);

        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
        addView(view, params);

        toolbar_editText = (EditText) this.findViewById(R.id.toolbar_editText);
        toolbar_textView = (TextView) this.findViewById(R.id.toolbar_textView);
        toolbar_imgBtn = (ImageButton) this.findViewById(R.id.toolbar_imgBtn);
        toolbar_LeftimgBtn = (ImageButton) this.findViewById(R.id.toolbar_leftImgBtn);
        toolbar_search = (TextView) this.findViewById(R.id.toolbar_search);
        toolbar_editText.addTextChangedListener(this);
        toolbar_imgBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != btnListenter) {
                    btnListenter.ImageRightBtnclick();
                }
            }
        });

        toolbar_LeftimgBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != btnListenter) {
                    btnListenter.ImageLeftBtnclick();
                }

            }
        });
        toolbar_search.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != btnListenter) {
                    if(TextUtils.isEmpty(toolbar_editText.getText())){
                        Toast.makeText(getContext(),"输入为空",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    btnListenter.searchBtnclick(toolbar_editText.getText().toString());
                }
            }
        });
        toolbar_editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    Log.e("editText", "失去焦点");
                    // 失去焦点
                    toolbar_editText.setCursorVisible(false);
                    InputMethodManager imm = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(toolbar_editText.getWindowToken(), 0);
                }else{
                    Log.e("editText", "获得焦点");
                    toolbar_editText.setCursorVisible(true);
                }
            }
        });

    }

    public void showTextView() {
        toolbar_textView.setVisibility(View.VISIBLE);
    }

    public void showEditText() {
        toolbar_editText.setVisibility(View.VISIBLE);
    }

    public void showRightBtnIcon() {
        toolbar_imgBtn.setVisibility(View.VISIBLE);
    }

    public void showLeftBtnIcon() {
        toolbar_LeftimgBtn.setVisibility(View.VISIBLE);
    }

    public void showToolbar_search(){
        toolbar_search.setVisibility(View.VISIBLE);
    }

    public void hintToolbar_search(){
        toolbar_search.setVisibility(View.GONE);
    }
    public void hintTextView() {
        toolbar_textView.setVisibility(View.GONE);
    }

    public void hintEditText() {
        toolbar_editText.setVisibility(View.GONE);
    }

    public void hintRightBtnIcon() {
        toolbar_imgBtn.setVisibility(View.GONE);
    }




    @Override
        public void setTitle(@StringRes int resId) {
        showTextView();
        if (resId != 0) {
            toolbar_textView.setText(resId);
        }
    }
    @Override
    public void setTitle(CharSequence title) {
        initView();
        showTextView();
        if (title != null) {
            toolbar_textView.setText(title);
        }
    }

    public void setLeftImageBtnDrawable(Drawable resId) {
        showLeftBtnIcon();
        toolbar_LeftimgBtn.setImageDrawable(resId);
    }

    public void setLeftImageBtnDrawable(int resId) {
        showLeftBtnIcon();
        toolbar_LeftimgBtn.setImageResource(resId);
    }

    public void setRightImageBtnDrawable(Drawable resId) {
        showRightBtnIcon();
        toolbar_imgBtn.setImageDrawable(resId);
    }

    public void setRightImageBtnResource(int resId) {
        showRightBtnIcon();
        toolbar_imgBtn.setImageResource(resId);
    }


    public void setMyToolBarBtnListenter(MyToolBarBtnListenter btnListenter) {
        this.btnListenter = btnListenter;
    }

    public void setMyToolBarEditTextListener(MyToolBarEditTextListener editTextListener) {
        this.editTextListener = editTextListener;
    }

    /**
     * Log.i(TAG, "输入文本之前的状态");
     *
     * @param s
     * @param start
     * @param count
     * @param after
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (null != editTextListener) {
            editTextListener.beforeTextChanged(s, start, count, after);
        }
    }

    /**
     * Log.i(TAG, "输入文字中的状态,");
     *
     * @param s
     * @param start
     * @param before
     * @param count
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (null != editTextListener) {
            editTextListener.onTextChanged(s, start, before, count);
        }
    }

    /**
     * Log.i(TAG, "输入文字后的状态");
     *
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {
        if(TextUtils.isEmpty(s)){
            showRightBtnIcon();
            hintToolbar_search();
        }else {
            hintRightBtnIcon();
            showToolbar_search();
        }
        if (null != editTextListener) {
            editTextListener.afterTextChanged(s);
        }
    }

    public interface MyToolBarBtnListenter {
        void ImageRightBtnclick();
        void ImageLeftBtnclick();
        void searchBtnclick(String content);
    }

    public interface MyToolBarEditTextListener {
        void beforeTextChanged(CharSequence s, int start, int count, int after);

        void onTextChanged(CharSequence s, int start, int before, int count);

        void afterTextChanged(Editable s);
    }
}


2.2自定义属性

    <declare-styleable name="MyToolBar">
        <attr name="RightImgButtonIcon" format="reference"></attr>
        <attr name="LeftImgButtonIcon" format="reference"></attr>
        <attr name="isShowEditText" format="boolean"></attr>
        <attr name="editHint" format="string"/>
    </declare-styleable>
2.3 组合空间布局

<?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="wrap_content">


    <EditText
        android:id="@+id/toolbar_editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:layout_marginRight="60dp"
        android:drawableLeft="@mipmap/ic_search"
        android:hint="请输入搜索内容"
        android:background="@null"
        android:visibility="gone"
         />

    <TextView
        android:id="@+id/toolbar_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="主页"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:visibility="gone" />

    <ImageButton
        android:id="@+id/toolbar_imgBtn"
        android:background="@null"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@mipmap/ic_share_normal"
        android:layout_marginRight="10dp"
        android:visibility="gone"
         />

    <ImageButton
        android:id="@+id/toolbar_leftImgBtn"
        android:background="@null"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:src="@mipmap/ic_launcher"
        android:visibility="gone"
         />

    <TextView
        android:id="@+id/toolbar_search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:text="搜索"
        android:background="@drawable/toolbar_search_bg"
        android:padding="10dp"
        android:visibility="gone"
        />

</RelativeLayout>

2.4 最终的 MyToolBar布局

<yu.cai.caishop.widget.MyToolBar
        android:id="@+id/myToolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        app:RightImgButtonIcon="@mipmap/ic_share_normal"
        app:LeftImgButtonIcon="@mipmap/ic_back_normal"
        app:title="蔡宇奎"
        app:isShowEditText="false"  
        app:editHint="请输入"
        ></yu.cai.caishop.widget.MyToolBar>

这里 默认 isShowEditText   是为false,为true 则显示 EditText。







  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值