EditText showing numbers with 2 decimals at all times

五迷三道 提交于 2019-11-29 01:55:19

Here is something I use to for dollar input. It makes sure that there are only 2 places past the decimal point at all times. You should be able to adapt it to your needs by removing the $ sign.

    amountEditText.setRawInputType(Configuration.KEYBOARD_12KEY);
    amountEditText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {}
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
            {
                String userInput= ""+s.toString().replaceAll("[^\\d]", "");
                StringBuilder cashAmountBuilder = new StringBuilder(userInput);

                while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
                    cashAmountBuilder.deleteCharAt(0);
                }
                while (cashAmountBuilder.length() < 3) {
                    cashAmountBuilder.insert(0, '0');
                }
                cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
                cashAmountBuilder.insert(0, '$');

                amountEditText.setText(cashAmountBuilder.toString());
                // keeps the cursor always to the right
                Selection.setSelection(amountEditText.getText(), cashAmountBuilder.toString().length());

            }

        }
    });
Andrew Ripa

Update #2

Correct me if I'm wrong, but oficial docs to TextWatcher say that it's legitimate use afterTextChanged method for make changes to... EditText content for this task.

I have the same task in my multy-language app and as I know it's possible , or . symbols as separator so I modify nickfox answer for 0.00 format with total limit of symbols to 10:

Layout (Updated):

<com.custom.EditTextAlwaysLast
        android:id="@+id/et"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:maxLength="10"
        android:layout_marginTop="50dp"
        android:inputType="numberDecimal"
        android:gravity="right"/>

EditTextAlwaysLast class:

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.EditText;

/**
 * Created by Drew on 16-01-2015.
 */
public class EditTextAlwaysLast extends EditText {

    public EditTextAlwaysLast(Context context) {
        super(context);
    }

    public EditTextAlwaysLast(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EditTextAlwaysLast(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onSelectionChanged(int selStart, int selEnd) {
    //if just tap - cursor to the end of row, if long press - selection menu
        if (selStart==selEnd)
            setSelection(getText().length());
       super.onSelectionChanged(selStart, selEnd);
}


}

Code in ocCreate method (Update #2):

EditTextAlwaysLast amountEditText;
    Pattern regex;
    Pattern regexPaste;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        amountEditText = (EditTextAlwaysLast)findViewById(R.id.et);


        DecimalFormatSymbols dfs = new DecimalFormatSymbols(getResources().getConfiguration().locale);
        final char separator =  dfs.getDecimalSeparator();

        //pattern for simple input
        regex = Pattern.compile("^(\\d{1,7}["+ separator+"]\\d{2}){1}$");
        //pattern for inserted text, like 005 in buffer inserted to 0,05 at position of first zero => 5,05 as a result
        regexPaste = Pattern.compile("^([0]+\\d{1,6}["+separator+"]\\d{2})$");

        if (amountEditText.getText().toString().equals(""))
            amountEditText.setText("0"+ separator + "00");

        amountEditText.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
                if (!s.toString().matches(regex.toString())||s.toString().matches(regexPaste.toString())){

                    //Unformatted string without any not-decimal symbols
                    String coins = s.toString().replaceAll("[^\\d]","");
                    StringBuilder builder = new StringBuilder(coins);

                    //Example: 0006
                    while (builder.length()>3 && builder.charAt(0)=='0')
                        //Result: 006
                        builder.deleteCharAt(0);
                    //Example: 06
                    while (builder.length()<3)
                        //Result: 006
                        builder.insert(0,'0');
                    //Final result: 0,06 or 0.06
                    builder.insert(builder.length()-2,separator);
                    amountEditText.setText(builder.toString());
                }
                amountEditText.setSelection(amountEditText.getText().length());
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

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

        });
    }

It's look like the best result for me. Now this code support copy-paste actions

Just some minor changes to the solutions that patrick posted. I've implemented everything in the onFocusChangedListener. Also be sure to set the EditText input type to "number|numberDecimal".

Changes are: If input is empty then replace with "0.00". If input has more than two decimals of precision, then cast down to two decimals. Some minor refactoring.

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override public void onFocusChange(View v, boolean hasFocus) {
    if (!hasFocus) {
        String userInput = ET.getText().toString();

        if (TextUtils.isEmpty(userInput)) {
            userInput = "0.00";
        } else {
            float floatValue = Float.parseFloat(userInput);
            userInput = String.format("%.2f",floatValue);
        }

        editText.setText(userInput);
    }
}
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!