使用自定义XML属性创建复合控件

Min*_*Dez 9 android android-layout

我一直在尝试将TextView和EditText组合到一个复合控件中,该控件使用自定义xml元素为每个单独的元素传递默认值.我一直在看这里的教程/文档:
构建复合控件
传递自定义属性

到目前为止我有什么.

Attrs.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>
Run Code Online (Sandbox Code Playgroud)

我的主要布局:

<?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>
Run Code Online (Sandbox Code Playgroud)

我的复合控制,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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Min*_*Dez 8

当你在寻求帮助后立即发现问题时,我讨厌它.

问题是我的自定义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>
Run Code Online (Sandbox Code Playgroud)

  • 而且我喜欢这样一个事实,即您在寻求帮助后立即注意到问题,而不是之前!您已经为我节省了很多时间在其他地方寻找相同的答案。谢谢! (5认同)