Updated 20 November 2017
All the view classes defined in the Android Framework extend View class. so,our custom view can also extend View directly, or indirectly by extending its subclasses, such as Button.
In this blog we can define and apply custom attribute for our custom View. so, How can we define custom attribute for custom attribute?
Define Custom Attribute-
To add a built-in View
to our user interface, we specify it in an XML element and control its appearance and behavior with element attributes. Well-written custom views can also be added and styled via XML. To enable this behavior in our custom view, we must:
<declare-styleable>
resource element
1 2 3 4 5 6 7 8 9 |
<resources> <declare-styleable name="CustomView"> <attr name="showText" format="boolean" /> <attr name="labelPosition" format="enum"> <enum name="left" value="0"/> <enum name="right" value="1"/> </attr> </declare-styleable> </resources> |
Once we define the custom attributes, we can use them in layout XML files just like built-in attributes. The only difference is that your custom attributes belong to a different namespace. Instead of belonging to the http://schemas.android.com/apk/res/android
namespace, they belong to http://schemas.android.com/apk/res/[your package name]
.
1 2 3 4 5 6 7 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews"> <com.example.customviews.charting.PieChart custom:showText="true" custom:labelPosition="left" /> </LinearLayout> |
Apply Custom Attribute to view-
When a view is created from an XML layout, all of the attributes in the XML tag are read from the resource bundle and passed into the view’s constructor as an AttributeSet
. so, how we apply these attribute to our Custom Attribute?
The Android resource compiler does a lot of work for us to make calling obtainStyledAttributes()
,this function returns TypedArray class object and we can obtained all the Attributes values from this object.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public CustomView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.CustomView, 0, 0); try { mShowText = a.getBoolean(R.styleable.CustomView_showText, false); mTextPos = a.getInteger(R.styleable.CustomVIew_labelPosition, 0); } finally { a.recycle(); } |
References: https://developer.android.com/
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.