链接两个 EditText 框以进行单位转换

发布于 2024-10-18 14:54:28 字数 356 浏览 2 评论 0原文

我试图想出一种可扩展的方法将两个编辑文本框链接在一起以进行单位转换。用户可以在其中一个框中输入一个值,转换后的值将显示在另一个框中。

我通常会这样做,这样当编辑一个 EditText 时,它会获取输入,通过一种方法传递它以转换值并设置另一个字段的文本。

问题是我有很多这样的对,每对都用于转换不同种类的单位。如果我为每个框使用 TextWatcher,您可以看到哪里会开始失控。

我考虑过扩展 TextWatcher,以便可以将 EditText 视图及其合作伙伴的视图传递给它,但我不确定如何传递它需要使用哪种转换方法。我可以为每种转换分配一个 int 并使用 switch,但这对我来说似乎不是一个好的解决方案。

有更好的办法吗?

I'm trying to come up with a scalable way to link two edit text boxes together for unit conversion. The user would enter a value in either of the boxes and the converted value would show up in the other.

I would normally just make it so when one EditText was edited, it would get the input, pass it through a method to convert the value and set the text of the other field.

The problem is I have a lot of these pairs and each pair is used to convert a different kind unit. If I used a TextWatcher for each box, you can see where that would start to get out of hand.

I thought about extending the TextWatcher so I could pass it the EditText View and its partner's view, but I'm not sure how to pass it what kind of conversion method needs to be used. I could assign an int to each kind of conversion and use a switch, but that doesn't seem like a good solution to me.

Is there a better way?

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

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

发布评论

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

评论(1

守望孤独 2024-10-25 14:54:28

我就是这样做的。创建一个类,例如 PartnerEditTextInfo ,其中包含参考号和 EditText 对象。将此作为标签附加到应用程序中的每个 EditText。将 PartnerEditTextInfo 中的 editText 设置为合作伙伴 editText,并具有唯一的参考号。因此,每个 EditText 都可以找到它的伙伴。

扩展 EditText 类并重写 onTextChanged() 方法来调用通用转换方法(可以是静态类静态方法)。通过获取文本发生变化的editText的标签对象,即可获取伙伴editText。然后,根据更改的 editText 对(基于参考编号)应用所需的转换公式,并对该对中的两个 editText 执行 setText。

注意 - 您需要有一种方法来确保不会进入无限循环,并有某种标志来区分用户对 editText 文本所做的更改和转换方法所做的更改。

This is how I would do it. Create a class, say PartnerEditTextInfo ,which contains a reference number and a EditText obj. Attach this as a tag to every EditText in your app. Set the editText in the PartnerEditTextInfo to the partner editText and have a unique reference number. Thus every EditText can get a hold of its partner.

Extend the EditText class and over ride onTextChanged() method to call a common conversion method(This can be a static class static method) . You can get the partner editText by getting the tag object of the editText whose text has changed. Then ,based on which pairs of editText(based on reference number) is changed apply required conversion formula and do the setText on both the editTexts in the pair.

Caution- You need have a way to make sure you wont get into a infinite loop, have some sort of flag to differentiate changes to editText's text made by user and made by the conversion method.

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