我正在使用EditText来允许用户输入存储在Double中的值。
但是,默认情况下,双打看起来像" 0.0"如果用户没有使用额外的十进制数,那么对于用户来说,它有点令人讨厌。有没有办法强制显示整数看起来像" 0"并且只有在用户实际决定使用它时才显示小数?
当前代码:
myEditText = (EditText) view.findViewById(R.id.my_edittext);
myEditText.setText(myVariable + "");
myEditText.addTextChangedListener(new TextWatcher() {
@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 s) {
String temp = s.toString();
if (s.length() > 0){
if (OtherMethods.isDouble(temp)) {
myVariable = Double.parseDouble(temp);
}
else {
myVariable = 0.0;
}
}
else {
myVariable = 0.0;
}
}
});
XML:
<EditText
android:id="@+id/my_edittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:hint="Input Value"
android:imeOptions="actionDone"/>
答案 0 :(得分:1)
将Double解析为String,然后将String解析为Int:
String stringparsed = YourDouble + "";
int intparsed = Integer.parseInt(stringparsed);
使用子字符串将字符串从startIndex剪切为finalIndex:
String stringparsed = YourDouble + "";
String final = stringparsed.substring(0,1); //for example, if the double was 0.0, the result is 0
答案 1 :(得分:1)
要实现此目的,您可以使用NumberFormat
EditText yourEditText = (EditText) findViewById(R.id.editTextID);
//dummy data, will have user's value
double aDouble = 4.0;
//formats to show decimal
NumberFormat formatter = new DecimalFormat("#0");
//this will show "4"
yourEditText.setText(formatter.format(aDouble));
确保验证用户的输入。此外,这只会修改显示的内容而不是值本身。