开发者

Creating Compound Controls With Custom XML Attributes

开发者 https://www.devze.com 2023-02-11 00:15 出处:网络
I\'m been trying to combine a TextView and an EditText into one compound control which uses custom xml elements to pass in default values for each individual element. I\'ve been looking at the tutoria

I'm been trying to combine a TextView and an EditText into one compound control which uses custom xml elements to pass in default values for each individual element. I've been looking at the tutorials/docs here:

Building Compound Controls

Passing Custom Attributes

What I have so far.

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>

My Main Layout:

<?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" 
     开发者_如何学Go   android:layout_height="wrap_content"
        myapp:label="label"
        myapp:default="default"
    />
</LinearLayout>

My Compound Control, 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();
    }
}

When I run the program I see the views OK but the value of my CharSequence, s, is always null. Can someone tell me where I'm going wrong?


I hate it when you notice the problem right after you ask for help.

The problem was that my namespace for my custom XML elements should have been like so:

<?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>
0

精彩评论

暂无评论...
验证码 换一张
取 消