如何自定义 EditText 框以仅允许货币?

发布于 2024-10-14 09:30:15 字数 344 浏览 3 评论 0原文

我是开发新手,我刚刚开始进入令人畏惧的验证世界。到目前为止,我已经很容易了,并且能够仅用这两行来限制输入类型:android:inputType="phone" android:digits="1234567890。"

现在我想尝试停止我的用户输入的数字超过小数点后两位。我想我要么需要使用 InputFilter 或使用 onTextChange 来检查小数点和数字的使用(唉,我也不知道我将如何去做)。我对这两个方面都没有经验,而且我很难在网上找到我能理解的例子,如果有人能告诉我从哪里开始,我将非常感激,我认为我走在正确的轨道上,但是我什至不确定如何检查字符,更不用说限制它们了。欢迎任何答案,谢谢。

i'm new to development and i'm just starting my journey into the daunting world of validation. So far i've had it easy and been able to restricted the inputtype just with these two lines: android:inputType="phone" android:digits="1234567890."

Now i want to try and stop my user from entering digits past two decimal places. I think i either need to be working with an InputFilter or using onTextChange to check for use of the decimal and digits thereafter( alas i don't have a clue how i would go about doing that either). I've got no experience with either of these and i'm having a hard time finding examples online that i can understand, If someone could tell me where to start that would be really appreciated, i think i'm on the right track but im not even sure how i'd go about checking characters let alone restricting them. Any answers welcome, thank you.

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

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

发布评论

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

评论(1

不语却知心 2024-10-21 09:30:16

创建一个实现 TextWatcher 的类

class CurrencyFormatterTextWatcher implements TextWatcher {

   @Override
   public synchronized void afterTextChanged(Editable text) {
        // [...] do your formatting here; beware that each 
        // change to the text value will fire another textchanged event
   }
}

,然后将其注册为目标 EditText 触发的 textchanged 事件的侦听器:

currencyFormatter = new CurrencyFormatterTextWatcher();
currencyEditText.addTextChangedListener(currencyFormatter);

Create a class that implements TextWatcher

class CurrencyFormatterTextWatcher implements TextWatcher {

   @Override
   public synchronized void afterTextChanged(Editable text) {
        // [...] do your formatting here; beware that each 
        // change to the text value will fire another textchanged event
   }
}

then register it as a listener for textchanged events fired by your targeted EditText:

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