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>

我的外部控件包括标签和ThirtySecondIncrement控件。我想使外部控件足够灵活,以至于可以在外部控件中包括“ countertype”样式。 我可以在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);
            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中进行此操作。 谢谢,谢谢

iCMS 回答:android嵌套自定义控件的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);
    //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函数仅设置变量,不会强制重绘,使我能够从包含自定义控件的构造函数中调用它。 任何,这就是我解决的方式。

本文链接:https://www.f2er.com/1989903.html

大家都在问