理解 Android 中的 R 类

在机器人中,我不确定我是否完全理解 R类。我将通过数独的例子,我有这样一段代码:

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) ...
}

我对 Java 还是个新手,但是从我收集到的信息来看,它似乎正在接受输入(触摸屏被触摸到按钮上)并评估参数。然后,如果 about 按钮被识别,则设置 case 语句,并创建一个新的界面屏幕,然后在手机上导航到该屏幕。

是这样吗?

如果我的大意是正确的,为什么要用“ R”类?

为什么要调用它来识别按钮的 ID?

我认为(在这个项目中)超类是 SudokuActivity 类。

107913 次浏览

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.

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.

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.