如何添加" + 91"并删除" + 91"在android中编辑文本?

时间:2016-07-01 05:44:33

标签: android

我有一项活动,当用户输入手机号码我想要添加" + 91"在号码之前以及当用户删除完整号码时我想删除" + 91"我也能这样做

TextWatcher m_MobileWatcher = 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 (!s.toString().contains("+91")) {
            m_InputMobie.setText("+91" + s.toString());
            Selection.setSelection(m_InputMobie.getText(), m_InputMobie.getText().length());
        }
    }
};

1 个答案:

答案 0 :(得分:5)

尝试以下代码,这项工作正常,我已经检查过了。

TextWatcher m_MobileWatcher = 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) {
            String text_value = m_InputMobie.getText().toString().trim();
            if(text_value.equalsIgnoreCase("+91"))
            {
                m_InputMobie.setText("");
            }else
            {
                if(!text_value.startsWith("+91") && text_value.length()>0) {
                    m_InputMobie.setText("+91" + s.toString());
                    Selection.setSelection(m_InputMobie.getText(), m_InputMobie.getText().length());
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };