在设置金额输入框的时候,只需要数字,而且往往有精确度限制,这里默认精确度是小数点后面1位。
代码:
1、布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
<EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:gravity="center" android:hint="请输入" android:inputType="numberDecimal" android:textSize="20sp" />
</RelativeLayout>
2、Java代码
public class MainActivity extends Activity {
EditText et;
/** * 用于控制小数点后面的位数。这里默认设置,如果输入了小数点,后面最多只能有1位 */
private static final int ACCURACYNUM = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.et);
et.addTextChangedListener(watcher);
}
private TextWatcher watcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String temp = s.toString().trim();
//如果数据以小数点开头,就清空。因为手机的处理速度,怎么也比手动输入的速度快,所以给人感觉是:开头输小数点,输不进去
if (s.toString().startsWith(".")) {
et.setText("");
}
int posDot = temp.indexOf(".");
if (posDot <= 0)
return;
if (temp.length() - posDot - 1 > ACCURACYNUM) {
s.delete(posDot + ACCURACYNUM + 1, posDot + ACCURACYNUM + 2);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
};
}