Defining custom attrs

前端 未结 5 1768
耶瑟儿~
耶瑟儿~ 2020-11-22 05:27

I need to implement my own attributes like in com.android.R.attr

Found nothing in official documentation so I need information about how to define these

5条回答
  •  无人共我
    2020-11-22 05:39

    if you omit the format attribute from the attr element, you can use it to reference a class from XML layouts.

    • example from attrs.xml.
    • Android Studio understands that the class is being referenced from XML
      • i.e.
        • Refactor > Rename works
        • Find Usages works
        • and so on...

    don't specify a format attribute in .../src/main/res/values/attrs.xml

    
    
    
        
            ....
            
            ....
        
    
    
    

    use it in some layout file .../src/main/res/layout/activity__main_menu.xml

    
    
    
        
        
    
    
    

    parse the class in your view initialization code .../src/main/java/.../MyCustomView.kt

    class MyCustomView(
            context:Context,
            attrs:AttributeSet)
        :View(context,attrs)
    {
        // parse XML attributes
        ....
        private val giveMeAClass:SomeCustomInterface
        init
        {
            context.theme.obtainStyledAttributes(attrs,R.styleable.ColorPreference,0,0).apply()
            {
                try
                {
                    // very important to use the class loader from the passed-in context
                    giveMeAClass = context::class.java.classLoader!!
                            .loadClass(getString(R.styleable.MyCustomView_give_me_a_class))
                            .newInstance() // instantiate using 0-args constructor
                            .let {it as SomeCustomInterface}
                }
                finally
                {
                    recycle()
                }
            }
        }
    

提交回复
热议问题