So, I said that I am going to make more posts and I told myself that these posts would have less complaining. Thus, I made this little tutorial...
What is R?
To start, R is an automatically generated class which allows you to access your resources (that's why it's called R, not L). Every file you put into your resources folder will have an int variable assigned to it which you can access when you want to use this resource.
For example:
Let's say that we have an image named "Ben.png" Now, in order to use this image we are going to have to write something like this:
R.drawable.Ben
Like I've said before, this returns an int. The drawable part of the syntax is because I put my image into one of the drawable folders (there are multiple folders due to how android handles varying pixel densities on different phones) Now, many of the functions in android will take this int and use it accordingly. I may or may not write more on this topic later on in a different blog post. We'll see.
Unfortunately, this isn't a very good way to get a large number of resources through something like a loop. We could record down the ints that are generated by going through the gen folder and looking at what the compiler has generated them to be. Instead of trying to get the ints through calling the variable, we get the ints through a string. This way you can number your images a1 a2 a3 a4 a5 a6 etc. (since the image names are made into variable names, there is no way you can add images to the res folder with names that start with numbers) To save and time and frustration in the future, let's write a function to do the work for us (again, I'm focusing on images in the drawable folders, adapt and adjust this as needed):
public static int GetIntFromString(Context context, String name) {
return (context.getResources().getIdentifier(name, "drawable", context.getPackageName()));
}
There isn't much to explain with this function but if you don't understand it, don't worry. Place this function in one of your classes and then you are able to access your drawables through a string.
While you may say that this is too simple to be worth making into a function, it's worth it. This is a little known way of getting your android resource through a string. If you are developing for iOS and figuring out how to get images or other files, through strings, now you know.
That's it for this time. Now you know the basics of R and what it does.
No comments:
Post a Comment