什么是更好的android.R或自定义R?

rds*_*rds 14 convention android coding-style

当我开始开发Android应用程序时,我倾向于在任何需要的地方定义自定义R值,特别是在布局文件中.例如:

findViewById(R.id.customerName).setText(customer.getName())
Run Code Online (Sandbox Code Playgroud)

布局:

<TextView android:text="TextView" android:id="@id/customerName"
    android:layout_height="wrap_content" android:layout_width="fill_parent" />
Run Code Online (Sandbox Code Playgroud)

现在我意识到,使用它可能会更好android.R.

findViewById(android.R.id.text1).setText(customer.getName())
Run Code Online (Sandbox Code Playgroud)

布局:

<TextView android:text="TextView" android:id="@android:id/text1"
    android:layout_height="wrap_content" android:layout_width="fill_parent" />
Run Code Online (Sandbox Code Playgroud)

你遵循什么样的做法?各有哪些优缺点?

jon*_*ohn 17

android.R 用于利用操作系统内置的资源.

您可以使用的操作系统附带许多图像/布局/等等 android.R

如果你正在引用您已经创建了自己的资源,经常使用R.,在大多数情况下,我建议您尝试远离内置客场资源,因为他们改变版本的升级.


rds*_*rds 0

框架 id与布局中的自定义 id没有太大的优点或缺点。

使用框架标识符的优点:

  • 避免创建更多标识符。在 apk 中保存一个字段(并且有 apk 大小限制)。
  • 在某些情况下必须使用,例如ListActivity

使用框架标识符的缺点:

  • 不要提供描述性名称

在这两种实践中

  • 该代码将来可以工作
  • 缺失的引用在运行时被发现,并在编译时隐藏

我认为 SDK 中的示例可以帮助我做出决定,但(你猜怎么着?)事实并非如此。Notepad 和 LunarLander 应用程序使用android.R.id来作为视图标识符,而 ApiDemos 项目使用自定义标识符。

混合了两种方法的 GestureBuilder 的最佳实践?(@+id/addButton@android:id/empty

IHMO,HelloActivity 和 JetBoy 的更糟糕做法定义了@+id/text @+id/Button01...这不是描述性的,可以用 (@andoid:id/button1@+id/startButton)代替