How to create own XML attribute in Custom View (Android)
Hey guys!
In this article, I’m gonna show you how you can create your XML attribute. app:is_underlined=false
like this, cool….😎 isn’t it? We will be making a custom view in which we will create an attribute to underline the text.
Just follow the steps along with me. 👀
Step 1: Create an XML file that will hold the attribute reference. You can define the name and input type of the attribute in <attr …
tag.
Here, the name of our attribute is is_underlined
and the input type is boolean
which accepts either true
or false
.
Step 2: Now, Let’s create our custom view with the help of the following piece of code.
Now, I am going to explain each and everything in the above code.
obtainStyledAttributes: This method is used to getTypedArray
by passing the attribute set and the reference of the styleable that we have created at first.
getBoolean: We used this method to get the value of the boolean passed in the XML file. We gave the default value as false.
Paint.UNDERLINE_TEXT_FLAG: We used this to underline the text.
recycle(): It recycles the TypedArray
, to be re-used by a later caller. After calling this function you must not ever touch the typed array again.
Step 3: Okay! Now it's time to use the custom view with is_underlined
attribute.
Yeah, You did it… 🙌
Thanks for your time 😁
Enjoy learning🥂