Android View 的 id 可以在多个 Activity 之间安全共享吗?
假设我的 Android 应用程序中有两个 Activity:EditPerson
和 EditEmployee
。
让 EditPerson
Activity 作为 EditEmployee
Activity 的基类并定义将数据编组到布局中定义的视图或从布局中定义的视图编组数据的方法似乎很自然。 EditPerson
Activity 的实现会将(例如)“Name”字段推送到 EditText
元素或从中推送。 EditEmployee
版本将调用基类版本,然后编组其自己的专用字段(例如税号等)。
为了促进共享代码,两个活动都必须有一个布局资源,该资源定义一对或多对共享相同 id 的 EditText
元素。即在 layout\edit_person.xml
中会有:
<EditText android:id="@+id/name_editor" />
然后在 layout\edit_employee.xml
中会有这样的内容:
<EditText android:id="@+id/name_editor" />
<EditText android:id="@+id/tax_id_editor" />
<!-- etc. -->
由于“Employee”是一个“Person”,并且有一些共同的字段(通过继承编组),看起来分配的 id(上例中的“name_editor”)只需在活动(或布局?)的范围内是唯一的。
从我的测试来看,这似乎有效,但我很怀疑这种方法和使用不明确的布局元素 id 会产生无意的副作用。谁能确认这是一种安全的做法和/或指出它最终将如何破坏我的申请?有人做过类似的事情吗?
Say I have two Activities in an Android application, EditPerson
and EditEmployee
.
It would seem natural to have the EditPerson
Activity be a base class for the EditEmployee
Activity and define methods that marshal data to and from the Views defined in the layout. The EditPerson
Activity's implementation would push (for example) the "Name" field to and from an EditText
element. The EditEmployee
versions would call the base class version, and then marshal its own specialized fields (say a tax id, etc.).
To facilitate the shared code, both activities would have to have a layout resource that defines one or more pairs of EditText
elements that share the same id. i.e. in layout\edit_person.xml
there would be:
<EditText android:id="@+id/name_editor" />
And then in layout\edit_employee.xml
there would be something like:
<EditText android:id="@+id/name_editor" />
<EditText android:id="@+id/tax_id_editor" />
<!-- etc. -->
Since the "Employee" is a "Person", and there are fields in common (marshaled via inheritance), it would seem as if the id assigned ("name_editor" in the above example) only has to be unique within the scope of an activity (or layout?).
From my testing, this appears to work, but I am paranoid that there would be a unintentional side effect to this approach and use of ambiguous layout element ids. Can anyone confirm that this is a safe practice and/or point out how it will eventually blow up my application? Has anyone ever done similar things?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很常见并且可以使用。特别是当您想要重用代码/类但使用不同的布局时。
It's common and ok to use. Especially intended when you want to reuse code/classes, but use different layouts.