java - 在 Android 中映射 XML 属性和代码方法

标签 java android xml

我正在尝试创建自定义 Android 复合 View ,代码如下:

<?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;
    }
...
}

属性.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 加载?

最佳答案

重写你的构造函数如下:

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();
}

关于java - 在 Android 中映射 XML 属性和代码方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6387464/

相关文章:

java - Hibernate孤儿移除-事务隔离级别

xml - 在 XSLT 中获取父元素

xml - NServiceBus 端点是否可以使用不同的序列化程序处理和发布?

java - 循环和 BufferedReader 的问题

java - 在我的应用程序中在哪里打开和关闭 SessionFactory

java - 使用 JMeter 对 CassandraDB 进行负载测试

android - Flutter - 从现有的 android 项目导入

android - picasso 没有加载图像

android - 阻止用户从缩放级别 15 map v2 android 缩小

xml - Spring 3.1 : Cannot find the declaration of element 'beans'