Android View 的 id 可以在多个 Activity 之间安全共享吗?

发布于 2024-09-12 02:19:41 字数 958 浏览 3 评论 0原文

假设我的 Android 应用程序中有两个 Activity:EditPersonEditEmployee

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.xmlthere 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

单身狗的梦 2024-09-19 02:19:41

很常见并且可以使用。特别是当您想要重用代码/类但使用不同的布局时。

It's common and ok to use. Especially intended when you want to reuse code/classes, but use different layouts.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文