I've got a custom component containing two TextViews that have a custom size-setting method on (the two text views are proportional by about a 1:2 ratio). Being that this is a subclass of RelativeLayout, it doesn't have a textSize attribute, but I'm wondering if it is possible to still set the android:textSize
attribute in the XML instantiation for this component, and then grab the textSize
attribute from the AttributeSet to use with my custom setSize()
method in the constructor.
I've seen the technique to do this with custom attributes, but what if I want to grab an attribute that's already in the android lexicon?
The accepted answer is a little long. Here is a condensed version that I hope will be easy to follow. In order to add a
textSize
attribute (or anything that usesdp
/sp
) to your custom view, do the following steps.1. Create a custom attribute
Create (or add the following section) to attrs.xml. Note the
dimension
format.2. Set the attribute in your xml layout.
Note the custom
app
namespace.3. Get the attribute value in your custom view
Note the use of
getDimensionPixelSize
. Within your custom view just work with pixels. See this answer if you need to convert to a different dimension.Notes
yes it is possible;
let's assume your RelativeLayout declaration (in xml) has textSize defined with 14sp:
In the constructor of your custom view (the one that takes in the AttributeSet), you can retrieve the attributes from Android's namespace as such:
The value of the xmlProvidedSize will be something like this "14.0sp" and maybe with little bit of String editing you can just extract the numbers.
Another option to declare your own attribute set would be little lengthy, but it is also possible.
So, you have your custom view and your TextViews declared something like this right:
great...
Now you need to also make sure your custom view overrides the constructor that takes in the AttributeSet like this:
ok, let's see that init() method now:
You're probably wondering where does R.styleable.MyCustomView, R.styleable.MyCustomView_text1Size and R.styleable.MyCustomView_text2Size are coming from; allow me to elaborate on those.
You have to declare the attribute name(s) in your attrs.xml file (under values directory) so that where ever you get to use your custom view, the values gathered from these attributes will be handed in your constructor.
So let's see how you declare the these custom attributes like you've asked: Here is my whole attrs.xml
Now you can set your TextViews' size in your XML, but NOT without declaring the namespace in your Layout, here is how:
Please pay attention how I declared the namespace to be "josh" as the first line in your CustomView's attribute set.
I hope this helps Josh,