As the title asks, I want to correctly monitor an Edit Text field to format the entered numbers as a currency with a "." being l=placed or inserted after the last 2 digits of the cell.

In all as the user inputs the numbers and the field expands the EditText will reflect that the numbers that they entered will reflect as a currency, example below:

user enters "123456"

the EditText will reflect this as : "1234.56" or even : "$1234.56"

I have tried a number of different techniques and believe that the section of code may need to be pleased within a TextWatcher which I currently have to clear the field if a user clicks on the field as well as the enabling of a button once a correct Boolean value is received after checking 2 fields.

the pieces of code that I will show below currently work, and I simply need the appropriate code and location to achieve the above stated needs.

This sections reflects my TextWatcher section:

        TextWatcher textWatcher = new TextWatcher(){
@Override
public void afterTextChanged(Editable s) {
    calcbtn.setEnabled(isready());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int count,int after) {

}
    };
    numofpep.addTextChangedListener(textWatcher); //Links to the TextWatcher element for afterTextChanged function
    billtotal.addTextChangedListener(textWatcher);//Links to the TextWatcher element for afterTextChanged function
    }

Any suggestions or comments are welcome.

cchinchoy

有帮助吗?

解决方案

Something Like this should do it:

    @Override
        public void afterTextChanged(Editable s) {
            String val = billTotal.getText().toString();
            String newStringContent = convertToDollarsAndCents(val);
            // change string to reflect your desired format
            billTotal.setText(newStringContent)
        }

        public String convertToDollarsAndCents(String val) {
          if(!val.contains(".") {
            if(val.length<=2) {
              return val+".00"
            }
            else {
               return val.subString(0, val.length-2)+"."+val.subString(val.length-2, val.length)
            }
          }
        }

The substring code might not be exactly right, but it ought to get it done with some tweaking.

The other option is to make your input a number input as you can configure an inputType for your EditText:

<EditText android:inputType="number" ... />

ANd put the onus on the user to indicate if they want cents or not.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top