This question already has an answer here:
- What is the class R in Android? 3 answers
In android, I'm not sure I quite understand the R
class. I'm going through the sudoku example, and I have this snippet of code:
switch (v.getId()) // the id of the argument passed is evaluated by switch statement
{
case R.id.about_button: //
Intent i = new Intent(this, about.class);
startActivity(i);
break;
// More buttons go here (if any) ...
}
I'm brand new to Java, but from what I gather it looks like it's taking input (the touch screen being touched on the button) and evaluating the argument. Then the case statement is setup if the about button is recognized, and a new interface screen is created and then navigated to on the phone.
Is this right?
If I got the gist of that correct, why is the deal with the "R" class?
Why is it called to recognize the ID of the button?
I thought the super class (in this project) was the SudokuActivity class.
R
is a class that contains ONLY public constants. (public static final).It is a generated class (by Android Plugin in Eclipse) that reflects the various values you defined in the
res
file.For instance, you should have something like:
somewhere in one of your layout/menu xml file in the project, and once you wrote that, Eclipse will generate a constant in the R file (which you can find it under
gen/PACKAGE/R.java
)Read the Resource guide in Android Developers for more information about this.
R
class is generated by Android tools from your resources before compiling your code. It contains assigned numeric constant for each resource that you can refer in your project. For example, you have XML resource file that containsabout_button
. If you didn't haveR
class, you would have to use a string "about_button" to refer to it in code. If you make a mistake in this string, you will only learn about it when you run your application. WithR
you will see the error much earlier at compile time.R
is structured in such a way that you can refer to resources via its inner classes. For example,R.id
contains id constants andR.layout
contains layout constants.R.java
is the dynamically generated class, created during build process to dynamically identify all assets (from strings to android widgets to layouts), for usage in java classes in Android app. Note thisR.java
is Android specific (though you may be able to duplicate it for other platforms, its very convenient), so it doesn't have much to do with Java language constructs. Take a look here, for more details.