package com.example.astart;
import java.text.DecimalFormat;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
public class MyUtils {
/**
* 格式化小数
* @param context
* @param paEditTexts
* @param limit 保留小数位数
*/
public static void setEditTextAccuracys(final Context context,final int limit,EditText...paEditTexts){
if(paEditTexts == null) return;
for (int i = 0; i < paEditTexts.length; i++) {
setEditTextAccuracy(context,paEditTexts[i],limit);
}
}
/**
* 格式化小数
* @param context
* @param editText
* @param limit 0 不限制小数位数
*/
private static void setEditTextAccuracy(final Context context,final EditText editText, final int limit) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(limit != 0){
/**
* 限制输入金额最多为 limit 位小数
*/
if (s.toString().contains(".")) {
if (s.length() - 1 - s.toString().indexOf(".") > limit) {
s = s.toString().subSequence(0,
s.toString().indexOf(".") + limit + 1);
editText.setText(s);
editText.setSelection(s.length());
}
}
}
/**
* 第一位输入小数点的话自动变换为 0.
*/
if (s.toString().trim().substring(0).equals(".")) {
s = "0" + s;
editText.setText(s);
editText.setSelection(2);
}
/**
* 避免重复输入小数点前的0 ,没有意义
*/
if (s.toString().startsWith("0")
&& s.toString().trim().length() > 1) {
if (!s.toString().substring(1, 2).equals(".")) {
editText.setText(s.subSequence(0, 1));
editText.setSelection(1);
return;
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable edit) {
}
});
if(limit != 0){
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if(!hasFocus){
if(!editText.getText().toString().isEmpty()){
try {
double value = Double.parseDouble(editText.getText().toString());
DecimalFormat format = new DecimalFormat("0.00");
editText.setText(format.format(value));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
}
}
使用
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText monkey;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
monkey=(EditText) findViewById(R.id.et_monkey);
MyUtils.setEditTextAccuracys(this, 2, monkey);
//上下文,最多保留几位小数,EditText控件名
}
}