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

在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">

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容