【发布时间】: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 始终为空。谁能告诉我哪里出错了?
【问题讨论】: