Understand the R class in Android [duplicate]

2019-01-02 20:55发布

This question already has an answer here:

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.

标签: java android
3条回答
高级女魔头
2楼-- · 2019-01-02 21:13

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:

android:id="@+id/about_button"

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.

查看更多
刘海飞了
3楼-- · 2019-01-02 21:17

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 contains about_button. If you didn't have R 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. With R 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 and R.layout contains layout constants.

查看更多
谁念西风独自凉
4楼-- · 2019-01-02 21:30

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 this R.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.

查看更多
登录 后发表回答