美文网首页
Android中简单的自定义属性步骤

Android中简单的自定义属性步骤

作者: zerone1 | 来源:发表于2017-04-09 21:35 被阅读0次

    在attrs文件中:
    <?xml version="1.0" encoding="utf-8"?>
    <resources>

    <declare-styleable name="CnToolbar">
    
        <attr name="rightButtonIcon" format="reference"/>
        <attr name="isShowSearchView" format="boolean"/>
    
    </declare-styleable>
    

    </resources>

    在代码中:也就是toolbar的子类的构造函数中:

    public CnToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

        if(attrs !=null) {
            final TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs,
                    R.styleable.CnToolbar, defStyleAttr, 0);
    
    
            final Drawable rightIcon = a.getDrawable(R.styleable.CnToolbar_rightButtonIcon);
            if (rightIcon != null) {
                //setNavigationIcon(navIcon);
                setRightButtonIcon(rightIcon);
            }
    
    
            boolean isShowSearchView = a.getBoolean(R.styleable.CnToolbar_isShowSearchView,false);
    
            if(isShowSearchView){
    
                showSearchView();
                hideTitleView();
    
            }
    
    
            a.recycle();
        }
    
    }
    

    最后就可以在xml代码中运用自定义的自定义属性了
    <cniao5.com.cniao5shop.widget.CnToolbar
    android:id="@+id/toolbar"
    android:background="?attr/colorPrimary"
    android:layout_width="match_parent"
    app:isShowSearchView="true"
    android:minHeight="?attr/actionBarSize"
    android:layout_height="wrap_content">

    相关文章

      网友评论

          本文标题:Android中简单的自定义属性步骤

          本文链接:https://www.haomeiwen.com/subject/wkrjattx.html