gpt4 book ai didi

android - 在 Java 代码中获取自定义属性的值

转载 作者:行者123 更新时间:2023-12-04 00:28:29 24 4
gpt4 key购买 nike

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

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

在我的代码中,我得到了这样的属性值:attrs.getAttributeIntValue("我的命名空间", "src", -1);

它有效。我从布局 xml 文件中获取“src”的值。但我的问题是为什么 android 不在 R 类中生成一个值,这样我就不需要在我的 java 代码中再次使用字符串 'src'?

最佳答案

改为使用 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();
}

关于android - 在 Java 代码中获取自定义属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10135329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com