【发布时间】:2012-07-18 16:04:19
【问题描述】:
最近我遇到了在 xml 布局中将自定义 xml 参数添加到我的视图中的问题。我知道我应该为此目的使用 attrs.xml 文件,但是......我发现,我可以使用自定义参数而根本没有任何 attrs.xml 文件。有人可以解释一下吗?这是一个错误还是一个有效的案例?
这是我的自定义视图:
public class TestView extends View {
public TestView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public TestView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
final String scheme = "http://red.com/ui/scheme";
if (attrs != null) {
Log.d("TestView", "custom param value: " + attrs.getAttributeValue(scheme, "cutom"));
}
}
}
这里是主要布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:red="http://red.com/ui/scheme"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<com.red.ui.TestView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffAABBCC"
red:cutom="customvalue"
/>
</LinearLayout>
这是一个简单的临时项目,由 Android 向导创建。
【问题讨论】:
-
我一直在寻找类似的东西,因为我发现需要“attrs.xml”有点烦人。在项目之间共享自定义视图似乎变得更加复杂。但是,您的上述解决方案对我不起作用:当我从 attrs.xml 中删除我的自定义属性时,布局 xml 将无法编译......它显示“包 'y' 中属性 'x' 没有资源标识符”,表示该属性必须在 attrs.xml 中声明,否则解析器将无法识别它。