Android editext textwatcher thousand separator no lag or slow

Android editext textwatcher thousand separator no lag or slow

I’m a bit curious that editext using textwatcher to manipulate into thousand comma separator perform really slow after lolipop version.
Mostly the tutorial shared the solution is remove and add listener on TextWatcher and make manipulation directly to EditText.
Performance issue is the issue from this approach.

Here are snippet for edittext thousand separator with TextWatcher that fast and no lag.

1
2
3
4
5
6
7
8
9
10
11
<EditText
    android:id="@+id/offer_price"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:inputType="number"
    android:selectAllOnFocus="true"
    android:hint="@string/hint_price"
    android:digits="0123456789.,"
    android:textColor="@color/md_black_1000"
    android:textSize="@dimen/_12sdp" />

and the implementation of TextWatcher

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
private TextWatcher thousandSeparatorListener() {
    // Change number into thousand separated by comma

    return new TextWatcher() {
        boolean isFormating;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {


        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(isFormating) return;
            isFormating = true;

            String str = editable.toString().replaceAll( "[^\\d]", "" );

            if(str.length() > 0) {
                double s1 = Double.parseDouble(str);

                NumberFormat nf2 = NumberFormat.getInstance(Locale.ENGLISH);
                ((DecimalFormat)nf2).applyPattern("#,###,###");
                editable.replace(0, editable.length(), nf2.format(s1));
            }

            isFormating = false;
        }
    };
}

Hope this can help to make thousand separator comma Edittext easily!

Leave a Reply

Your email address will not be published. Required fields are marked *