AttributeSet

android.util
接口 AttributeSet

所有已知子接口:
XmlResourceParser

public interface AttributeSet

A collection of attributes, as found associated with a tag in an XML document. Often you will not want to use this interface directly, instead passing it to Resources.Theme.obtainStyledAttributes() which will take care of parsing the attributes for you. In particular, the Resources API will convert resource references (attribute values such as "@string/my_label" in the original XML) to the desired type for you; if you use AttributeSet directly then you will need to manually check for resource references (with getAttributeResourceValue(int, int)) and do the resource lookup yourself if needed. Direct use of AttributeSet also prevents the application of themes and styles when retrieving attribute values.

This interface provides an efficient mechanism for retrieving data from compiled XML files, which can be retrieved for a particular XmlPullParser through Xml.getAttributeSet(). Normally this will return an implementation of the interface that works on top of a generic XmlPullParser, however it is more useful in conjunction with compiled XML resources:

 XmlPullParser parser = resources.getXml(myResouce);
 AttributeSet attributes = Xml.getAttributeSet(parser);

The implementation returned here, unlike using the implementation on top of a generic XmlPullParser, is highly optimized by retrieving pre-computed information that was generated by aapt when compiling your resources. For example, the getAttributeFloatValue(int, float) method returns a floating point number previous stored in the compiled resource instead of parsing at runtime the string originally in the XML file.

This interface also provides additional information contained in the compiled XML resource that is not available in a normal XML file, such as getAttributeNameResource(int) which returns the resource identifier associated with a particular XML attribute name.

自定义变量 AttributeSet的使用  

1.在attrs.xm里面定义
<resources>
<declare-styleable name="MyListViewAttrs">
<attr name="enablePullRefresh" format="boolean"  />
</declare-styleable>
</resources>
 
2.在layout xml中
前面名字域中增加
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:myapp="http://schemas.android.com/apk/res/
com.test.wb>
 
<com.test.wb.CommentRetweetList
android:id="@+id/commentlist" 
android:layout_width="fill_parent"
android:layout_height="0dip" 
android:layout_weight="1"
android:divider="#cccfd3"
android:dividerHeight="1px"
android:fadingEdge="vertical"
android:visibility="gone"
myapp:enablePullRefresh="false"/>
 
 
3.程序中
if(attrs != null){  
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyListViewAttrs);
.//将取到layout里面的值“false”,如果没有,就是默认的值true  
mPullRefreshEnable = a.getBoolean(R.styleable.MyListViewAttrs_enablePullRefresh, true);  
a.recycle();  
}
 
原文地址:https://www.cnblogs.com/benxiong/p/2830737.html