如何通过 Android 中的方向变化保持动态视图聚焦?

发布于 2024-10-01 14:33:30 字数 390 浏览 0 评论 0原文

我有一个活动,顶部有一个 EditText,里面有一个带有 LinearLayout 的 ScrollView。

LinearLayout 在 onCreate 方法中填充了一组基于随初始 Intent 传递的对象的动态视图。这通常是一组 EditText。

结果是一个 EditText 列表,每个 EditText 对应于不同的数据(并且正在编辑的数据集变化很大,因此需要像这样动态创建列表)。

问题是,当这些视图之一具有焦点并且方向发生变化(例如用户翻出键盘进行键入)时,焦点会捕捉到 Activity 最顶部的 EditText。这当然是不受欢迎的行为,因为当用户翻出键盘时,他/她并不打算输入顶部的 EditText。

我怎样才能动态创建这样的视图列表,并且不会出现这种不良的焦点改变行为?

I have an activity with an EditText on top and a ScrollView with a LinearLayout inside it.

The LinearLayout is populated in the onCreate method with a set of dynamic views based on an object passed with the initiating Intent. This is typically a set of EditTexts.

The result is a list of EditTexts each corresponding to a different piece of data (and the dataset being edited is quite variable, so the list needs to be created dynamically like this).

The problem is, when one of these views has focus, and the orientation changes (say the user flips out the keyboard to type), the focus snaps to the EditText at the very top of the Activity. This is certainly undesired behavior as the user didn't intend to type in the top EditText when he/she flipped out the keyboard.

How can I dynamically create my list of views like this and not have this undesirable focus changing behavior?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

天邊彩虹 2024-10-08 14:33:30

结果我需要为每个动态 EditText 分配一个唯一且一致的 id。

Activity 无法正确保留焦点的原因是它无法重新定位视图,因为它没有 id。

Turns out I needed to assign a unique and consistent id to each of my dynamic EditTexts.

The reason the activity couldn't retain focus properly is it had no way of relocating the view because it had no id.

探春 2024-10-08 14:33:30

当方向发生变化时,将调用 onDestroy(),并且将使用 onCreate() 再次创建 Activity。这就是为什么焦点被捕捉到它找到的第一个 EditText 的原因。

您可能想看看这个:处理运行时更改

具体来说,本主题:在配置更改期间保留对象

When an orientation change occurs, onDestroy() is called, and the activity will be created again using onCreate(). That's why the focus is snapped at the first EditText that it finds.

You might want to have a look at this: Handling Runtime changes.

Specifically, this topic: Retain an object during configuration change

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