Pre*_*ier 71 android attributes view
什么是Android中的AttributeSet?
我如何将它用于我的自定义视图?
cap*_*wag 22
一个迟到的答案,虽然详细描述,为其他人.
AttributeSet(Android文档)
与XML文档中的标记关联的属性集合.
基本上,如果您尝试创建自定义视图,并且想要传递尺寸,颜色等值,则可以使用AttributeSet.
想象一下,你想在View下面创建一个类似的东西
有一个黄色背景的矩形,里面有一个圆圈,比方说5dp半径和绿色背景.如果希望视图通过XML获取背景颜色和半径的值,如下所示:
<com.anjithsasindran.RectangleView
app:radiusDimen="5dp"
app:rectangleBackground="@color/yellow"
app:circleBackground="@color/green" />
Run Code Online (Sandbox Code Playgroud)
那AttributeSet就是使用的地方.您可以将此文件包含attrs.xml在values文件夹中,并具有以下属性.
<declare-styleable name="RectangleViewAttrs">
<attr name="rectangle_background" format="color" />
<attr name="circle_background" format="color" />
<attr name="radius_dimen" format="dimension" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
由于这是一个View,因此java类扩展自 View
public class RectangleView extends View {
public RectangleView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.RectangleViewAttrs);
mRadiusHeight = attributes.getDimensionPixelSize(R.styleable.RectangleViewAttrs_radius_dimen, getDimensionInPixel(50));
mCircleBackgroundColor = attributes.getDimensionPixelSize(R.styleable.RectangleViewAttrs_circle_background, getDimensionInPixel(20));
mRectangleBackgroundColor = attributes.getColor(R.styleable.RectangleViewAttrs_rectangle_background, Color.BLACK);
attributes.recycle()
}
}
Run Code Online (Sandbox Code Playgroud)
所以现在我们可以RectangleView在xml布局中使用这些属性,我们将在RectangleView构造函数中获取这些值.
app:radius_dimen
app:circle_background
app:rectangle_background
Run Code Online (Sandbox Code Playgroud)
您可以使用AttributeSet为您在xml中定义的视图获取额外的自定义值.例如.有一个关于定义自定义属性的教程,其中指出"可以直接从AttributeSet读取值",但它没有说明如何实际执行此操作.但是,它确实警告说,如果你不使用样式属性,那么:
如果你想忽略整个样式属性并直接获取属性:
的example.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://www.chooseanything.org">
<com.example.CustomTextView
android:text="Blah blah blah"
custom:myvalue="I like cheese"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
注意有两行xmlns(xmlns = XML命名空间),第二行定义为xmlns:custom.然后在该自定义下面:定义myvalue.
CustomTextView.java
public CustomTextView( Context context, AttributeSet attrs )
{
super( context, attrs );
String sMyValue = attrs.getAttributeValue( "http://www.chooseanything.org", "myvalue" );
// Do something useful with sMyValue
}
Run Code Online (Sandbox Code Playgroud)