14

使用Kotin android 扩展我可以避免使用findViewById,但我不确定如何命名 id 以正确使用它。

我发现两个选项是:

  1. 对 id 使用简单的名称,但如果我将其与片段一起使用,我可能会在使用 espresso 时遇到麻烦

android.support.test.espresso.AmbiguousViewMatcherException: 'with id: .../mainLayout' 匹配层次结构中的多个视图。

这是因为我在 TabLayout 中有两个具有相同 id 的片段:

<LinearLayout android:id="@+id/mainLayout"
  1. 所有者姓名:"@+id/loginMainLayout""@+id/signUpMainLayout"

但后来我将不得不使用像signUpMainLayout.doSomething().

注意:我不喜欢_在这种情况下使用 ,因为这不是一个好的代码风格

还有哪些其他选择?

4

2 回答 2

3

我不知道你为什么不使用这个名字"@+id/loginMainLayout",什么时候在 Kotlin 和 Java 中很常见。用例将如您所说。"@+id/signUpMainLayout"lowerCamelCasesignUpMainLayout.doSomething()

无论如何,在整个应用程序中为 id 使用唯一名称是一个好习惯。这不是因为 Espresso 而是主要是当您看到 ID 的名称时知道视图与 ID 关联的位置。如果你使用这种风格并不难。例子:

fragment_contacts

<TextView id="+id/contactNameText 
android:text="John Smith" .../>

<ImageView id="+id/contactUserImage .../>

断言:因为知道它是Image一个.contactUserImageImageView

fragment_settings

<TextView id="+id/settingsNotificationText 
android:text="Turn notifications on/off" .../>

<checkBox id="+id/settingsNotificationCheck .../>
于 2017-05-18T15:56:05.950 回答
2

就我而言,我一直在使用此约定https://jeroenmols.com/blog/2016/03/07/resourcenaming/,但没有下划线和驼峰式约定。

如果您在将控件拖到视图时注意到,在 android studio 中,它会使用驼峰式大小写约定命名 id。

尽管变量的名称可能有点大,但您始终可以在变量声明中使用 val 或 var。

问候

于 2018-01-31T21:08:48.320 回答