Android: integer from xml resource

AndroidAndroid Resources

Android Problem Overview


How do I have to modify my XML resources, or what XML file do I have to create, to access integer values in the same way you access string values with R.string.some_string_resource ?

For example, in the code I want to say:

ProgressDialog progressBar = new ProgressDialog(getContext());
progressBar.setMax(getInteger(R.integer.maximum));

Is it possible?

Android Solutions


Solution 1 - Android

Yes it is possible, it would look like this:

  1. Create an xml resources file in the folder /res/values/ called integers.xml.

You are free to give it any name as you want, but choose one that is obvious.

  1. In that resources file, create your integer values.

    Your file then looks something like that:

     <?xml version="1.0" encoding="utf-8"?>
     <resources>    
         <integer name="maximum">100</integer>
         ...
    
     </resources>
    
  2. Reference the integer value in the Java code like this:

    It's a bit different from the getString(), you have to take a little detour.

     ProgressDialog progressBar = new ProgressDialog(getContext());
     int max = getContext().getResources().getInteger(R.integer.maximum);
     progressBar.setMax(max);
    

Solution 2 - Android

You must add the integers.xml file to your project

enter image description here

and then

enter image description here

and in integers.xml add this

<integer name="maximum">5</integer>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTerryView Question on Stackoverflow
Solution 1 - AndroidTerryView Answer on Stackoverflow
Solution 2 - Androidabolfazl bazghandiView Answer on Stackoverflow