137

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?

2 Answers 2

315

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.

  2. 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>
    
  3. 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);
    
Sign up to request clarification or add additional context in comments.

8 Comments

That's a double value, not an integer. Maybe you ask that in a separate StackOverflow question.
@Terry So is this the preferred method to use Integers in android, I usually hard code it in the code itself. What is your reccomendation?
@capt.swag Usually you hardcode integers as constants in the code in each class as appropriate. But if you need to have different constants for different layouts (ie number of columns for a grid) then you will use XML files to adapt that constant to various widths of the screen. Hope that helps
can i use that integer value directly in XML ?
@capt.swag yes, that's the preferred method
|
10

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.