Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant Value Between XML and Java

I know this is a simple question, so hopefully it won't be a bother to anyone.

How can I have a constant float value in my project that I can access from a View's XML and .java file?

I've tried setting a float value in my View's resource file as such:

<attr name="cornerRadius" format="float">15.0dp</attr>

I believe thats how it should be done, but I just did it using intuition. I'm really struggling on what to google on this subject.

Now, for accessing it in Java, I've tried this:

float myFloat = getContext().obtainStyledAttributes(attrs, R.styleable.MyView).getFloat(R.styleable.MyView_cornerRadius, 0.0f);

This is throwing me off, since its not getting the right value, but rather the value that I pass in the function. Why am I passing a float value to this function? There must be a different option.

Now, where the biggest problem is for me is accessing it in the XML.. I've tried this:

<corners android:radius="@attrs_my_view/cornerRadius"/>

I also tried this:

<corners android:radius="@float/cornerRadius"/>

But to no avail.

Maybe all of this is completely wrong, but I don't know how to search for this in google, because I don't know what its called. Its like having to look up a word in a dictionary based on its meaning. Its not a good time.

like image 817
RileyE Avatar asked May 31 '26 06:05

RileyE


1 Answers

You can create an XML file to contain your constants. This sounds like a dimension, which are standardly stored in the dimens.xml file. Place this in your res/values folder.

So, you might have a file (named dimens.xml), with the following in it:

<resources>
    <dimen name="cornerRadius">15dp</dimen>

</resources>

Then you can reference it using the normal R.class (ie. R.dimen.cornerRadius) - which you can reference from XML or Java.

like image 187
Booger Avatar answered Jun 01 '26 18:06

Booger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!