在Android中为视图创建自定义属性

要在Android中为视图创建自定义属性,需要在项目的res/values目录中的attrs.xml文件中声明自定义属性。以下是如何在attrs.xml中为视图定义自定义属性的示例:

<resources>
    <declare-styleable name="CustomView">
        <attr name="customAttribute" format="string"/> 
    </declare-styleable>
</resources>

在本例中,我们为CustomView视图定义了一个名为customAttribute自定义属性format属性指定自定义属性的数据类型,可以是字符串或者int或者颜色值等。在这种情况下,它被定义为一个字符串。

  • reference - 如果需要引用其他资源 (如: "@color/my_color", "@layout/my_layout")
  • color
  • boolean
  • dimension
  • float
  • integer
  • string
  • fraction
  • enum - 通常隐式的定义
  • flag - 通常隐式的定义
    你可以通过 |设置多个格式 , 如: format="reference|color"

enum 可以用如下方式定义:

<attr name="my_enum_attr">
  <enum name="value1" value="1" />
  <enum name="value2" value="2" />
</attr>

flag 是相似的,只是需要定义值,以便将它们位存储在一起:

<attr name="my_flag_attr">
  <flag name="fuzzy" value="0x01" />
  <flag name="cold" value="0x02" />
</attr>

一旦在attrs.xml中定义了自定义属性,就可以像其他任何属性一样在自定义视图的布局xml文件中使用它。以下是如何使用它的示例:

<com.example.CustomView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:customAttribute="Hello, world!" />

在此示例中,我们将 customAttribute属性的值设置为“Hello, world!”对于我们的 CustomView 视图。请注意,我们使用 app: 命名空间来引用我们的自定义属性

最后,通常在自定义视图的构造函数里访问自定义属性,如下:

public CustomView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  
  TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView, defStyle, 0);
   // R.styleable.CustomView_customAttribute 引用指向的是要访问的自定义属性的资源id
  String str = a.getString(R.styleable.CustomView_customAttribute);

  //do something with str

  a.recycle();
}

可能还需要把引用空间:

xmlns:whatever=“http://schemas.android.com/apk/res-auto”

替换成:

xmlns:whatever=“http://schemas.android.com/apk/res/org.example.mypackage”

whatever 可能是android,app或者tools

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值