What is AttributeSet and how can i use it?

前端 未结 4 535
谎友^
谎友^ 2020-12-24 00:04

What is AttributeSet in Android?

How can i use it for my custom view?

4条回答
  •  一个人的身影
    2020-12-24 00:48

    You can use AttributeSet to get extra, custom values for your view which you define in the xml. For example. There's a tutorial about Defining Custom Attributes which states, "it's possible to read values from the AttributeSet directly" but it doesn't say how to actually do this. It does warn, however, that if you don't use styled attributes then:

    • Resource references within attribute values are not resolved
    • Styles are not applied

    If you want to ignore the whole styled attributes thing and just get the attributes directly:

    example.xml

    
    
      
    
    
    

    Note there are two lines of xmlns (xmlns = XML namespace), the second is defined as xmlns:custom. Then below that custom:myvalue is defined.

    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
    }
    

提交回复
热议问题