我正在尝试创建自定义Android复合视图,这里是代码:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/linearLayout1">
<ImageView android:src="@drawable/icon"
android:id="@+id/action_imageView"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
</ImageView>
<TextView android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/action_text" android:layout_height="fill_parent"
android:layout_width="fill_parent" android:text="TextView">
</TextView>
</LinearLayout>
</merge>
ActionWidget.java(我正在处理的组件):
public class ActionWidget extends LinearLayout
{
...
public ActionWidget(Context context, AttributeSet attributeSet,
int defStyle)
{
super(context, attributeSet);
LayoutInflater inflater = (LayoutInflater)context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.action, this);
setClickable(true);
}
public void setLabel(String label)
{
TextView text = (TextView)findViewById(R.id.action_text);
text.setText(label);
}
public String getLabel()
{
return this.label;
}
...
}
attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ActionWidget">
<attr name="label" format="string" />
<attr name="image" format="integer" />
</declare-styleable>
</resources>
用法:
<com.someapp.form.ActionWidget
android:id="@+id/actionWidget1" android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:label="Text changed">
</com.someapp.form.ActionWidget>
当我启动应用程序时,文本仍然是“TextView”。 我该怎么做才能从xml加载它?
答案 0 :(得分:1)
重写构造函数,如下所示:
public ActionWidget(Context context, AttributeSet attributeSet, int defStyle){
super(context, attributeSet);
inflate(context, R.layout.action, this);
TypedArray attributes = context.obtainStyledAttributes(attributeSet,
R.styleable.ActionWidget);
CharSequence attrValue = attributes
.getString(R.styleable.ActionWidget_label);
if (attrValue != null)
setLabel(attrValue);
attributes.recycle();
}