获取Java中code自定义属性的值 [英] Get value of a custom attribute in Java Code

查看:280
本文介绍了获取Java中code自定义属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建文件attrs.xml一个属性:

I create an attribute in attrs.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Custom">
        <attr name="src" format="integer" />
    </declare-styleable>
</resource>

在我的code,我得到这样的属性的值:
attrs.getAttributeIntValue(myNameSpace对象,SRC,-1);

And in my code, I get the value of the attribute like this: attrs.getAttributeIntValue("mynamespace", "src", -1);

它的工作原理。我从布局xml文件'src'中的价值。
但我的问题是,为什么Android不产生R中类的值,这样我就不需要在我的Java code再次使用字符串'src'中?

It works. I get the value of 'src' from the layout xml file. But my question is why android does not generate a value in R class so that I don't need to use the string 'src' again in my java code?

比今天开始。

推荐答案

而不是使用的 TypedArray

Instead use the TypedArray

public CustomView(final Context context) {
    this(context, null);
}

public CustomView(final Context context,
            final AttributeSet attrs) {
    this(context, attrs, 0);
}

public CustomView(final Context context,
            final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);

    final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.Custom, defStyle, 0);

    int src = a.getInt(R.styleable.Custom_src, 0);

    a.recycle();
}

这篇关于获取Java中code自定义属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆