- 正好碰到这种情况,就记录下来吧,实现起来很简单
xml文件里加个靠右限制就把光标移到右边去了,初始值设置成0.00
- <EditText
- android:id="@+id/id_edit"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:gravity="center_vertical|right"
- android:numeric="integer"
- android:text="0.00" />
然后代码里实现
代码中要注意不要在字符未改变时对editText.setText,否则会报 StackOverflowError
- public class MainActivity extends Activity {
- EditText edit;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- edit = (EditText) findViewById(R.id.id_edit);
- edit.addTextChangedListener(new TextWatcher() {
- private boolean isChanged = false;
- @Override
- public void onTextChanged(CharSequence s, int start, int before,
- int count) {
- // TODO Auto-generated method stub
- }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count,
- int after) {
- // TODO Auto-generated method stub
- }
- @Override
- public void afterTextChanged(Editable s) {
- // TODO Auto-generated method stub
- if (isChanged) {// ----->如果字符未改变则返回
- return;
- }
- String str = s.toString();
- isChanged = true;
- String cuttedStr = str;
- /* 删除字符串中的dot */
- for (int i = str.length() - 1; i >= 0; i--) {
- char c = str.charAt(i);
- if ('.' == c) {
- cuttedStr = str.substring(0, i) + str.substring(i + 1);
- break;
- }
- }
- /* 删除前面多余的0 */
- int NUM = cuttedStr.length();
- int zeroIndex = -1;
- for (int i = 0; i < NUM - 2; i++) {
- char c = cuttedStr.charAt(i);
- if (c != '0') {
- zeroIndex = i;
- break;
- }else if(i == NUM - 3){
- zeroIndex = i;
- break;
- }
- }
- if(zeroIndex != -1){
- cuttedStr = cuttedStr.substring(zeroIndex);
- }
- /* 不足3位补0 */
- if (cuttedStr.length() < 3) {
- cuttedStr = "0" + cuttedStr;
- }
- /* 加上dot,以显示小数点后两位 */
- cuttedStr = cuttedStr.substring(0, cuttedStr.length() - 2)
- + "." + cuttedStr.substring(cuttedStr.length() - 2);
- edit.setText(cuttedStr);
- edit.setSelection(edit.length());
- isChanged = false;
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- }