关于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;
}
}
这样一个自定义属性的全部步骤就已经完成了,快去项目中试试把