EditText can only enter amount in Android development

Source: Internet
Author: User

Last time I wrote a blog that edittext can only enter the amount, later found a bug, when not yet entered a number in the case of the decimal point of the program to collapse, I went to check the payment treasure, see how, I entered the decimal point, the program is normal, I re-enter the number, can be normal input, but not perfect, because " .562 "How much is the money, I would like to add is that when the number has not been entered in the case of the decimal point, the digit automatically fill 0. Because the code is more redundant I went to the Internet to check the data, summed up a better way to achieve the edittext to add listening.

public class Money {
public static void Setpricepoint (final edittext edittext) {

Edittext.addtextchangedlistener (New Textwatcher () {
@Override
public void ontextchanged (charsequence s, int start, int before,
int count) {
if (S.tostring (). Contains (".")) {
if (S.length ()-1-s.tostring (). IndexOf (".") > 2) {
s = s.tostring (). subsequence (0,
S.tostring (). IndexOf (".") + 3);
Edittext.settext (s);
Edittext.setselection (S.length ());
}
}
if (s.tostring (). Trim (). substring (0). Equals (".")) {
s = "0" + s;
Edittext.settext (s);
Edittext.setselection (2);
}
if (s.tostring (). StartsWith ("0") && s.tostring (). Trim (). Length () > 1) {
if (!s.tostring (). substring (1, 2). Equals (".") {
Edittext.settext (s.subsequence (0, 1));
Edittext.setselection (1);
Return
}
}
}
@Override
public void beforetextchanged (charsequence s, int start, int count, int after) {

}
@Override
public void aftertextchanged (Editable s) {
TODO auto-generated Method Stub
}
});
}
}

It's easy to use.

Tv_price = (edittext) Findviewbyid (R.id.tv_price);
Money.setpricepoint (Tv_price);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.