Reputation: 13947
I am trying to make a custom view that will accept @null
on some property
<declare-styleable name="CustomButton">
<attr name="icon" format="reference"/>
</declare-styleable>
I want this parameter to accept @null
when I read it in the attrs, how do i find out that @null
was entered as opposed to this property not set at all ?
<CustomButton
....
app:icon="@null"
/>
val icon = ta.getDrawable(R.styleable.CustomButton_icon)
what comes here?
Upvotes: 2
Views: 708
Reputation: 7250
So I did my research and I found these points usefull and made my conclusion. It might help you.
First things first if you have some custom attribute, in this case, icon
when you specify some drawable reference to it i.e actually existing drawable reference for example
app:icon = "@drawable/some_drawable_that_does_exist"
the getDrawable()
returns the corresponding drawable mentioned.
Point 1: What if you don't mention icon in XML? (You are not writing @null
here)
Well In that case the getDrawable() will simply return null as drawable
Point 2: What if you mention icon as @null
in XML?
Well in this case also the getDrawble() will simply return null as the drawable
As I said earlier you can just use a simple check before doing your operations like this
val icon : Drawable? = ta.getDrawable(R.styleable.CustomButton_icon)
Note the type is Drawable? i.e nullable
even if you don't mention it explicitly it stills give you a nullable
type of drawable
So now, one simple condition
if(icon!=null) {
// Do your stuff here if it's not null
}else {
// Do your overriding behaviour if it's null
}
But wait. What is the purpose of mentioning @null
in XML if it still gives you the null as value and the same thing happens with not mentioning anything in xml.
So how to overcome this?
In order to overcome this, you need to set a global drawable for the icon in your styles.xml file like this
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="icon">@drawable/some_drawable_that_does_exists</item>
</style>
Notice: That is AppTheme
So we will have a common drawable for our view in app regardless you mention it in xml or not.
Even if you mention an icon in XML the mentioned icon will be used for rendering view.
Now if you mention @null on the view in XML your overriding condition mentioned in code will kicks in and you can do anything you want there.
Thanks.
Things to consider :
- Name your custom attributes unique so that they can't collide with existing android attributes
Upvotes: 1