There seems to be a lot of "similar" questions and answers to this scattered around which all refer to how to get a custom attribute from an AttributeSet
. What I haven't been able to find so far is how to get an android:
namespace tag:
似乎有很多“类似”的问题和答案分散在其中,所有问题都涉及如何从AttributeSet获取自定义属性。到目前为止我无法找到的是如何获取android:namespace标签:
<com.custom.view.StatusThumbnail
android:id="@+id/statusThumbnailContainer"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"/>
I would like to pull back the layout_height
attribute from this custom component. Unfortunately from what I've read the closest I've got to how to do this is:
我想从此自定义组件中拉回layout_height属性。不幸的是,根据我所读到的,我最接近的方法是:
public StatusThumbnail(Context context, AttributeSet attrs) {
super(context, attrs);
String height = attrs.getAttributeValue("android", "layout_height");
But this returns null
.
但是这会返回null。
Surely this isn't a rare thing to try and do?
当然这不是一件罕见的事情吗?
2 个解决方案
#1
58
The namespace should be "http://schemas.android.com/apk/res/android
" android is an alias declared in your xml file
命名空间应为“http://schemas.android.com/apk/res/android”android是在xml文件中声明的别名
#2
-1
First declare required attributes in :
首先声明所需的属性:
res\attrs.xml
水库\ attrs.xml
<declare-styleable name="StatusThumbnail">
<attr name="statusThumbnailattr" format="string"/>
</declare-styleable>
then in your XML layout declaration use the same attribute
然后在您的XML布局声明中使用相同的属性
<com.custom.view.StatusThumbnail
android:id="@+id/statusThumbnailContainer"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
statusThumbnailattr="some value"
android:layout_weight="1"/>
Access using
访问使用
public StatusThumbnail(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.StatusThumbnail);
this.mdColorDialogTitle=a.getString(R.styleable.StatusThumbnail_statusThumbnailattr);
}
#1
58
The namespace should be "http://schemas.android.com/apk/res/android
" android is an alias declared in your xml file
命名空间应为“http://schemas.android.com/apk/res/android”android是在xml文件中声明的别名
#2
-1
First declare required attributes in :
首先声明所需的属性:
res\attrs.xml
水库\ attrs.xml
<declare-styleable name="StatusThumbnail">
<attr name="statusThumbnailattr" format="string"/>
</declare-styleable>
then in your XML layout declaration use the same attribute
然后在您的XML布局声明中使用相同的属性
<com.custom.view.StatusThumbnail
android:id="@+id/statusThumbnailContainer"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
statusThumbnailattr="some value"
android:layout_weight="1"/>
Access using
访问使用
public StatusThumbnail(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.StatusThumbnail);
this.mdColorDialogTitle=a.getString(R.styleable.StatusThumbnail_statusThumbnailattr);
}