Android 嵌套的自定义控件 XML 属性



我正在构建一个 android 复合控件并将其嵌套到另一个复合控件中。 嵌套控件 ThirtySecondIncrement 是一个简单的递增控件,其中包含一个减号然后文本字段,然后是加号,因此您可以提高或降低增量。 我已使此控件在我的应用程序中更加通用,允许简单的计数器或 30 秒增量或 1 分钟增量。 这是 xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="counter_simple">0</integer>
<integer name="counter_30sec">1</integer>
<integer name="counter_1min">2</integer>
<declare-styleable name="ThirtySecondIncrement">
<attr name="countertype" format="integer"/>
<attr name="maxcount" format="integer"/>
</declare-styleable>
<declare-styleable name="IntervalEdit">
<attr name="label" format="string"/>
<attr name="incrementlabel" format="string"/>
</declare-styleable>
</resources>

我的外部控件包括标签和 ThirtySecond Increment 控件。 我想使外部控件足够灵活,以便我可以将"计数器类型"样式包含在外部控件中。 我可以在 xml 中执行此操作还是必须以编程方式执行此操作? 如果我以编程方式执行此操作,我如何保证在首次使用控件之前完成它。 下面是提取 xml 属性的代码:

public class ThirtySecondIncrement extends LinearLayout {
final int COUNT_INTEGER = 0;
final int COUNT_30SEC = 1;
final int COUNT_1MIN = 2;
//other code
public ThirtySecondIncrement(Context context, AttributeSet attr) {
super(context, attr);
TypedArray array = context.obtainStyledAttributes(attr, R.styleable.ThirtySecondIncrement, 0, 0);
m_countertype = array.getInt(R.styleable.ThirtySecondIncrement_countertype, COUNT_30SEC);
m_max = array.getInt(R.styleable.ThirtySecondIncrement_maxcount, MAXCOUNT);
m_increment = (m_countertype == COUNT_1MIN) ? 2 : 1;
array.recycle();
Initialize(context);
}

在我的 IntervalEdit 中的类似函数中,我可以获取与计数器相关的属性,并使用 ThirtySecondIncrement 中的公共函数来设置计数器类型,但如前所述,我想知道是否有办法在 xml 中执行此操作。 谢谢,提前

我等了一会儿,但没有得到答案,所以我通过在嵌套控件中有一个帮助程序函数来解决问题,以便在运行时设置属性。

public void SetCounterType(integer countertype) {
//after checking that countertype is a valid value
m_countertype = countertype;
}

然后在 IntervalEdit 的构造函数中:

public IntervalEdit(Context context, AttributeSet attrs) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.IntervalEdit, 0, 0);
//other attributes read here
m_counterstyle = array.getInt(R.styleable.IntervalEdit_counterstyle, R.integer.counter_simple);
(ThirtySecondIncrement)findViewById(R.id.tsi).SetCounterStyle(m_counterstyle);

第一个自定义控件中的 SetCounterStyle 函数仅设置变量,不强制重绘,使我能够从包含自定义控件的构造函数中调用它。 任何,这就是我解决它的方式。

最新更新