Android视图字段名称约定

tes*_*der 5 java android android-layout android-view

例如,我有id的视图:

<ImageButton
        android:id="@+id/imageButtonStart"
        android:layout_width="100dp"
        android:layout_height="100dp" />
Run Code Online (Sandbox Code Playgroud)

我是否需要使用相同名称的私有字段,如下所示:

private ImageButton imageButtonStart;
Run Code Online (Sandbox Code Playgroud)

zap*_*apl 5

我需要一个同名的私人字段吗?

不,android:id布局xml文件中不要求您在代码中使用具有相同名称的变量.

但是如果搜索id,则需要使用确切的名称

View randomName = findViewById(R.id.imageButtonStart);
Run Code Online (Sandbox Code Playgroud)

命名是很多个人偏好.您应该选择明确定义命名事物代表内容的名称.并且您应该与您的命名方案保持一致.

这个名称应该有多久是有争议的,有些人会选择startBtn,imageButtonStart因为它在你的代码中更短,更烦人.如果按钮是一个ImageButton与你的代码无关的事实,你不需要命名它imageButton,只是button足以让它清楚.

有些人喜欢使用具有分层方案的名称,其中最重要的区分符号首先出现.就像Java和Android包名com.google.market而不是market.google.com.

而不是startButtonendButton,他们选择buttonStartbuttonEnd.这背后的原因是你可以更有效地使用自动完成.如果你不记得你是否命名了结束按钮,endButton或者stopButton你需要查看整个提案列表.使用该buttonXYZ方案,您可以开始输入,button因为您知道它是一个按钮,并且只会获得一些提案.

上面也是一个很好的例子,为什么你应该保持一致.如果你命名一个按钮buttonStart而另一个按钮clickablethingStop则整个方案都没用.不一致的命名需要更多的时间来找到正确的东西,如果你选择了错误的东西可能会导致错误.

另一件事是你用于名字的语言.如果您只为自己或使用该语言的人编写代码,那么使用您自己的语言是完全可以的.但是,一旦你想与其他人分享,请留意英语.甚至错误的英文命名也比你根本不懂的语言更容易阅读和理解.

还有很多其他命名约定:WP:命名约定

例如Android 编码syle指南状态:

  • 非公开的非静态字段名称以m开头.
  • 静态字段名称以s开头.
  • 其他字段以小写字母开头.
  • 公共静态最终字段(常量)是ALL_CAPS_WITH_UNDERSCORES.

它会是private ImageButton mButtonStart;private static sSingletonThing;

如果您想要为Android源代码贡献,只需要使用该约定,您可以以任何风格编写自己的应用程序.

您应该遵循的唯一命名约定是通用Java类/方法/变量模式:(来自维基百科上面的链接)

  • 类名:UpperCamelCase
  • 方法名称:lowerCamelCase
  • 变量名称:lowerCamelCase
  • 常量:ALL_CAPS

它开始变得非常如果他们看了你的代码,为其他人混淆,你有小写的类名等.


Raw*_*ode 3

虽然保持一致并为变量使用相同的名称是一种很好的做法,但您不需要将类变量调用为与 XML 中的 id 相同的名称,因为您将在代码中手动将它们连接起来,例如:

ImageButton imageButtonNotStart = (ImageButton) this.findViewById(R.id.imageButtonStart);
Run Code Online (Sandbox Code Playgroud)

我个人偏好使用componentTypeDescriptiveName诸如imageButtonStartXML 之类的格式,但在代码中我更喜欢更英语驱动的方法,例如startButton.

通常我最终会得到

<ImageButton
        android:id="@+id/imageButtonStart"
        android:layout_width="100dp"
        android:layout_height="100dp" />

ImageButton startButton = (ImageButton) this.findViewById(R.id.imageButtonStart);
Run Code Online (Sandbox Code Playgroud)