Specify Custom View Style in Constructor

When you extend an Android View or one of it’s sub-classes to create your own custom view, there are three constructors you can define:

You can read about them on the developer web page for View. (Actually, there’s a fourth constructor added in API 21, but I’ll ignore that one.)

The third constructor is used to give your custom view a default style using the defStyleAtrr parameter, which you can define in a style xml, but it’s not clear from the documentation how you use it:

An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.

I was recently creating a custom EditText which (among other things) I didn’t want to have a cursor indicator:

select_handle

You can set this indicator (or select handle as it’s officially called) to any image you like using the textSelectHandle attribute in the view’s style. So I created an empty image in xml in the drawable folder:

and set this in the style I wanted to use for the custom control:

From there I thought all I needed to do was put this style id in the constructor of the custom view, and then when I create a new instance of the view in code it would have this style:

But it didn’t work. When I ran the app my custom control was displayed with no style at all.

After a bit of googling I found out there was one step I was missing. The clue is in the name of that third parameter: defStyleAttr, it needs to be a resource of type attribute, not a style. So I added an attribute resource in my styles.xml:

Then associated this attribute with the custom control’s style in the app’s main style:

And used this in the constructor:

And that did it. When I used my custom edit text control in the app, no cursor indicator was displayed when tapping on text in the control.

Leave a Reply

Your email address will not be published. Required fields are marked *