setting edittext value to zero when empty and removing zero when any entry is made

邮差的信 提交于 2021-01-28 02:52:11

问题


I have two edittext fields that i am using to display results of mathematical functions. I have two problems. I want to edit text to have a value of zero in two scenarios: 1st: I want the edit text value to automatically become zero if the edit text is empty

2nd: if a user erases field values till the edit text is empty.

UPDATE: The 1st problem I can sort with a setText() or android:text="0" but when trying to also solve the 2nd it becomes tricky


回答1:


Try something like this:

final EditText et = new EditText(this);
et.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) {
        if(et.getText().length() == 0){
            et.setText("0");
        }
    }
});



回答2:


yourEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){
                if(yourEditText.getText().length() == 1 && yourEditText.getText().toString().trim().equals("0")){
                    yourEditText.setText("");
                }
            }else {
                if(yourEditText.getText().length() == 0){
                    yourEditText.setText("0");
                }
            }
        }
    });



回答3:


use TextWatcher as folow :

yourEditText.addTextChangedListener(new TextWatcher() {
            @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
            }
        });

i hope this will help :)



来源:https://stackoverflow.com/questions/31804956/setting-edittext-value-to-zero-when-empty-and-removing-zero-when-any-entry-is-ma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!