AndroidStudio中自定义属性及使用

关于Android中自定义属性以及使用

在开发中必不可少的需要接触到自定义控件,那么我们需要使用的属性没有怎么办呢,那么就需要使用自定义属性来实现某些效果,下面就来详细介绍下在AndroidStudio中的使用吧


1.在values目录下创建attrs.xml文件

这里写图片描述

这里写图片描述

这里写图片描述

2.在attrs文件中写入以下代码

<resources>
    <declare-styleable name="SettingItemView"> <!-- 这个Name需要跟你的自定义View的名称一致哦 -->
        <attr name="title" format="string" /> <!-- 属性的名称以及值,这里属性的名称为title其值只能为String -->
        <attr name="hasShowImage" format="boolean" />
    </declare-styleable>
</resources>

3.在布局文件中使用

    <!-- 需要设置命名空间 在eclipse中apk 后面跟的是项目的根包的全路径,在AndroidStudio中得到优化直接res-auto就可使用 -->
  xmlns:john="http://schemas.android.com/apk/res-auto"
    <john.com.mobilesafe.view.SettingItemView
        android:id="@+id/setting_style_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/setting_item_selector_bottom"
        john:hasShowImage="false"
        john:title="设置风格设置" />

以上代码可以看出,自定义的title,hasShowImage这两个自定义属性的使用

3.在自定义View中获取相应的属性值

// 将设置给自定义控件的自定义属性的值获取出来,设置给textView显示
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SettingItemView, defStyleAttr, 0);
        for (int i = 0; i < typedArray.getIndexCount(); i++) {
            int attr = typedArray.getIndex(i);
            switch (attr) {
                case R.styleable.SettingItemView_title:
                    mTvTitle.setText(typedArray.getString(attr));
                    break;
                case R.styleable.SettingItemView_hasShowImage:
                    setVisibility(typedArray.getBoolean(attr, true));
                    break;
            }
        }

这样一个自定义属性的全部步骤就已经完成了,快去项目中试试把

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值