Creating default values ​​for custom attributes using styles and themes

I have several custom View in which I created custom style attributes declared in the xml layout and read during the view constructor. My question is: if I do not specify explicit values ​​for all user attributes when defining my layout in xml, how do I use styles and themes for the default value that will be passed to my View constructor?

For instance:

attrs.xml:

 <declare-styleable name="MyCustomView"> <attr name="customAttribute" format="float" /> </declare-styleable> 

layout.xml ( android: tags android: removed for simplicity):

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/com.mypackage" > <-- Custom attribute defined, get 0.2 passed to constructor --> <com.mypackage.MyCustomView app:customAttribute="0.2" /> <-- Custom attribute not defined, get a default (say 0.4) passed to constructor --> <com.mypackage.MyCustomView /> </LinearLayout> 
+6
source share
1 answer

After doing additional research, I realized that the default values ​​can be set in the constructor for the View itself.

 public class MyCustomView extends View { private float mCustomAttribute; public MyCustomView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView); mCustomAttribute = array.getFloat(R.styleable.MyCustomView_customAttribute, 0.4f); array.recycle(); } } 

The default value can also be loaded from the xml resource file, which can vary depending on the screen size, screen orientation, SDK version, etc.

+6
source

Source: https://habr.com/ru/post/917234/


All Articles