Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one use Resources.getFraction()?

How do I store a fractional value like 3.1416 in resources? What to write in the XML and how to retrieve it in Java code?

The documentation for getFraction() states:

public float getFraction (int id, int base, int pbase)

Retrieve a fractional unit for a particular resource ID.

Parameters
base The base value of this fraction. In other words, a standard fraction is multiplied by this value.
pbase The parent base value of this fraction. In other words, a parent fraction (nn%p) is multiplied by this value.

Returns
Attribute fractional value multiplied by the appropriate base value

This answer shows a simple example of percentages without going into the details of what the arguments mean.

like image 940
Dheeraj Vepakomma Avatar asked Jul 31 '12 06:07

Dheeraj Vepakomma


People also ask

What is the use of resource ID in Android?

drawable for all drawable resources) and for each resource of that type, there is a static integer (for example, R. drawable. icon ). This integer is the resource ID that you can use to retrieve your resource.

What is a resource in Android studio?

Resources are the additional files and static content that your code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more.


1 Answers

You specify fractions in XML as so:

   <item name="fraction" type="fraction">5%</item>    <item name="parent_fraction" type="fraction">2%p</item> 

Where 5% would be 0.05 when actually used.

Then:

// 0.05f getResources().getFraction(R.fraction.fraction, 1, 1); // 0.02f getResources().getFraction(R.fraction.parent_fraction, 1, 1); // 0.10f getResources().getFraction(R.fraction.fraction, 2, 1); // 0.10f getResources().getFraction(R.fraction.fraction, 2, 2); // 0.04f getResources().getFraction(R.fraction.parent_fraction, 1, 2); // 0.04f getResources().getFraction(R.fraction.parent_fraction, 2, 2); 

As you can see, depending on the type of fraction, the getFraction method multiples the values accordingly. If you specify a parent fraction (%p), it uses the second argument (pbase), ignoring the first. On the other hand, specifying a normal fraction, only the base argument is used, multiplying the fraction by this.

like image 77
Rich Avatar answered Sep 18 '22 20:09

Rich