最近,我遇到了在xml布局中将自定义xml参数添加到视图中的问题。我知道我应该为此使用attrs.xml文件,但是...我发现,我可以在没有任何attrs.xml文件的情况下使用自定义参数。有人能解释一下吗?这是一个bug,还是一个有效的案例?
以下是我的自定义视图:
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>这是一个简单的scratch项目,由Android向导创建。
发布于 2012-07-19 13:44:25
您添加的自定义属性在R.java中不可用,我认为制作自定义属性的主要座右铭是在多个地方使用它。但是通过这个代码,我们不能完成同样的场景。
以下是示例代码- attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyLayout">
<attr name="text" format="string" />
</declare-styleable>
</resources>我正在更改main.xml以添加文本属性
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:red="http://red.com/ui/scheme"
xmlns:myapp="http://schemas.android.com/apk/res/com.psl"
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"
myapp:text="Text String" />
<com.psl.TestView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffAABBCC"
myapp:text="My Special Text String"
red:cutom="customvalue" />
</LinearLayout>TestView.java -
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"));
}
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MyLayout);
CharSequence s = a.getString(R.styleable.MyLayout_text);
Log.d("MyTestView", "attrs param value: " + s.toString());
}
}如果您在attrs.xml中创建attr之后注意到了。它在任何地方都可用。但是,在xml中通过自定义名称空间定义的attr只能通过您必须在任何地方定义的名称空间来使用。这可能是一个错误,因为属性被添加到某个自定义名称空间,而不是在应用程序本身中。
发布于 2012-07-19 13:48:42
当然,这不是一个"bug“。这就是在xml中使用自定义视图的方式。请参考:http://developer.android.com/guide/topics/ui/custom-components.html
https://stackoverflow.com/questions/11545599
复制相似问题