什么 id 名称约定对 Kotlin android 扩展有好处
What id name convention is good for Kotlin android extensions
使用Kotin android extensions我可以避免使用findViewById
,但是
我不确定如何命名 ID 以正确使用它。
我找到了两个选项:
- 对 id 使用简单的名称 但是如果我将它与 fragments 一起使用,我可能会在使用 espresso 时遇到麻烦:
android.support.test.espresso.AmbiguousViewMatcherException: 'with id: .../mainLayout' matches multiple views in the hierarchy.
这是因为我在 TabLayout 中有两个具有相同 ID 的片段:
<LinearLayout android:id="@+id/mainLayout"
- 所有者名称:
"@+id/loginMainLayout"
和 "@+id/signUpMainLayout"
但是我将不得不使用像 signUpMainLayout.doSomething()
这样的变量。
Note: I dont like the use of _
in this case since that's not a good code style.
还有哪些选择?
我不明白为什么你不使用 "@+id/loginMainLayout"
和 "@+id/signUpMainLayout"
,而 lowerCamelCase
中的名称在 Kotlin 和 Java 中很常见。如您所说,用例将是 signUpMainLayout.doSomething()
。
无论如何,在整个应用程序中为 ID 使用唯一的名称是一种很好的做法。这不是因为 Espresso,而是主要是当您看到 ID 的名称时知道视图与 ID 关联的位置。如果你使用这种风格并不难。
示例:
在fragment_contacts
中:
<TextView id="+id/contactNameText
android:text="John Smith" .../>
<ImageView id="+id/contactUserImage .../>
断言:contactUserImage
中有 Image
因为知道它是一个 ImageView
.
在fragment_settings
中:
<TextView id="+id/settingsNotificationText
android:text="Turn notifications on/off" .../>
<checkBox id="+id/settingsNotificationCheck .../>
就我而言,我一直在使用这个约定 https://jeroenmols.com/blog/2016/03/07/resourcenaming/,
但没有下划线和骆驼大小写约定。
如果您注意到将控件拖动到视图时,在 android studio 中,它会使用驼峰命名法命名 id。
虽然变量名可能有点大,但您始终可以在变量声明中使用 val 或 var。
问候
使用Kotin android extensions我可以避免使用findViewById
,但是
我不确定如何命名 ID 以正确使用它。
我找到了两个选项:
- 对 id 使用简单的名称 但是如果我将它与 fragments 一起使用,我可能会在使用 espresso 时遇到麻烦:
android.support.test.espresso.AmbiguousViewMatcherException: 'with id: .../mainLayout' matches multiple views in the hierarchy.
这是因为我在 TabLayout 中有两个具有相同 ID 的片段:
<LinearLayout android:id="@+id/mainLayout"
- 所有者名称:
"@+id/loginMainLayout"
和"@+id/signUpMainLayout"
但是我将不得不使用像 signUpMainLayout.doSomething()
这样的变量。
Note: I dont like the use of
_
in this case since that's not a good code style.
还有哪些选择?
我不明白为什么你不使用 "@+id/loginMainLayout"
和 "@+id/signUpMainLayout"
,而 lowerCamelCase
中的名称在 Kotlin 和 Java 中很常见。如您所说,用例将是 signUpMainLayout.doSomething()
。
无论如何,在整个应用程序中为 ID 使用唯一的名称是一种很好的做法。这不是因为 Espresso,而是主要是当您看到 ID 的名称时知道视图与 ID 关联的位置。如果你使用这种风格并不难。 示例:
在fragment_contacts
中:
<TextView id="+id/contactNameText
android:text="John Smith" .../>
<ImageView id="+id/contactUserImage .../>
断言:contactUserImage
中有 Image
因为知道它是一个 ImageView
.
在fragment_settings
中:
<TextView id="+id/settingsNotificationText
android:text="Turn notifications on/off" .../>
<checkBox id="+id/settingsNotificationCheck .../>
就我而言,我一直在使用这个约定 https://jeroenmols.com/blog/2016/03/07/resourcenaming/, 但没有下划线和骆驼大小写约定。
如果您注意到将控件拖动到视图时,在 android studio 中,它会使用驼峰命名法命名 id。
虽然变量名可能有点大,但您始终可以在变量声明中使用 val 或 var。
问候