【问题标题】:Creating Compound Controls With Custom XML Attributes使用自定义 XML 属性创建复合控件
【发布时间】:2014-01-06 22:05:10
【问题描述】:

我一直在尝试将 TextView 和 EditText 组合成一个复合控件,该控件使用自定义 xml 元素为每个单独的元素传递默认值。我一直在看这里的教程/文档:
Building Compound Controls
Passing Custom Attributes

到目前为止我所拥有的。

属性.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="FreeText">
        <attr name="label" format="string" />
        <attr name="default" format="string" />
    </declare-styleable>
</resources>

我的主要布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myapp="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <com.example.misc.FreeText  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        myapp:label="label"
        myapp:default="default"
    />
</LinearLayout>

我的复合控件,FreeText:

public class FreeText extends LinearLayout {

    TextView label;
    EditText value;

    public FreeText(Context context, AttributeSet attrs) {
        super(context, attrs);

        this.setOrientation(HORIZONTAL);

        LayoutParams lp = new LayoutParams(0, LayoutParams.WRAP_CONTENT);
        lp.weight = 1;

        label = new TextView(context);
        addView(label, lp);

        value = new EditText(context);
        addView(value, lp);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FreeText);
        CharSequence s = a.getString(R.styleable.FreeText_label);
        if (s != null) { 
            label.setText(s);
        }

        a.recycle();
    }
}

当我运行程序时,我看到视图正常,但我的 CharSequence 的值 s 始终为空。谁能告诉我哪里出错了?

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    我讨厌你在寻求帮助后立即发现问题。

    问题是我的自定义 XML 元素的命名空间应该是这样的:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:myapp="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
        <com.example.misc.FreeText  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"
            myapp:label="label"
            myapp:default="default"
        />
    </LinearLayout>
    

    【讨论】:

    • 我很高兴您在寻求帮助后立即注意到了问题,而不是之前!您为我在其他地方寻找相同的答案节省了很多时间。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    相关资源
    最近更新 更多