我想在任何时候显示带有两位小数的EditText字段的输入。因此,当用户输入5时,它将显示5.00,或当用户输入7.5时,它将显示7.50。
除此之外,我想在字段为空而不是空的时候显示零。
我已经得到的输入类型设置为:
android:inputType="number|numberDecimal"/>
我应该在这里使用inputfilters吗?
对不起,我还是刚接触android / java ......
感谢您的帮助!
凭借nickfox的答案,我能够解决一半问题。
et.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(""))
{
et.setText("0.00");
Selection.setSelection(et.getText(), 0, 4);
}
}
});
我还在研究另一半问题的解决方案。如果我找到了解决方案,我也会在这里发布。
OnFocusChangeListener FocusChanged = new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
String userInput = et.getText().toString();
int dotPos = -1;
for (int i = 0; i < userInput.length(); i++) {
char c = userInput.charAt(i);
if (c == '.') {
dotPos = i;
}
}
if (dotPos == -1){
et.setText(userInput + ".00");
} else {
if ( userInput.length() - dotPos == 1 ) {
et.setText(userInput + "00");
} else if ( userInput.length() - dotPos == 2 ) {
et.setText(userInput + "0");
}
}
}
}
答案 0 :(得分:16)
这是我用来输入美元的东西。它确保始终只有小数点后2位。您应该可以通过删除$ 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());
}
}
});
答案 1 :(得分:3)
更新#2
如果我错了,请纠正我,但是TextWatcher的官方文档说它是合法的使用afterTextChanged
方法进行更改。 。此任务的EditText内容。
我的多语言应用程序中有相同的任务,因为我知道它可能是,
或.
符号作为分隔符,所以我修改了nickfox的答案为0.00格式符号总限制为10:
布局(已更新):
<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类:
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);
}
}
ocCreate方法中的代码(更新#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) {
}
});
}
对我来说,这看起来是最好的结果。现在这段代码支持复制粘贴操作
答案 2 :(得分:1)
对帕特里克发布的解决方案进行了一些小改动。我已经在onFocusChangedListener中实现了所有内容。另外一定要将EditText输入类型设置为“number | numberDecimal”。
变化是: 如果输入为空,则替换为“0.00”。 如果输入的精度小数超过两位,则转换为两位小数。 一些小的重构。
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);
}
}
});