-1

I have a requirement in my application such that I should assign ids to my dynamically created views, I don't want to use hard-code method to assign ids to resources. Is there is any way to fetch ids from R.java class and store them in an array and use with findviewbyid() method ?

Thanks in advance!!

2
  • If you need to assign specified R.id to your array, you can just assign the elements from R.java to a new Array. (ex: int[] ids = {R.id.item1, R.id.tem2, R.id.item3, .....}; Commented Mar 18, 2015 at 6:50
  • It is fine but,it would be little bit difficult of initializing ids array for more resouce id's statically. Is there is any way to do it dynamicall something like for(id.length){ store each id in ids array} ? Commented Mar 18, 2015 at 7:33

2 Answers 2

1

I think using java reflection to get all variables in class R will match your requirement, see this quesion and its answer.

Sign up to request clarification or add additional context in comments.

Comments

1

While using an integer array is a valid way of doing that, wouldn't it be easier using something which allows you to refer your resources by their name?

Try this (it uses reflection).

Add this method to your code:

protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
    final int ResourceID =
        ctx.getResources().getIdentifier(resName, resType,
            ctx.getApplicationInfo().packageName);
    if (ResourceID == 0)
    {
        throw new IllegalArgumentException
        (
            "No resource string found with name " + resName
        );
    }
    else
    {
        return ResourceID;
    }
}

And use it like this:

int myID =
    getResourceID("your_resource_name", "drawable", getApplicationContext());

Note: No path (and no extension, in case of images).
Note: Reflection can be used also to fetch by name other resource types, like strings and layouts as well.

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.