0

I'm trying to add some chars to the entering text in an EditText field, but the method append() is not working.

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.temp, container, false);
        button = (Button)rootView.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Dialog dialog = new Dialog(getActivity());
                dialog.setContentView(R.layout.enter_sms_dialog);
                dialog.setTitle(Html.fromHtml("<font color='#000000'>Phone number verification</font>"));
                edSmsCode = (EditText) dialog.findViewById(R.id.edSmsCode);
                edSmsCode.addTextChangedListener(new TextWatcher() {
                    int len = 0;
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        String str = edSmsCode.getText().toString();
                        len = str.length();
                    }
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {}
                    @Override
                    public void afterTextChanged(Editable s) {
                        String str = edSmsCode.getText().toString();
                        if (str.length() == 3 && len < str.length()) {
                            edSmsCode.append("-");
                        }
                    }
                });
                dialog.show();
            }
        });
        return rootView;
    }

But this method works when I use this code for an EditText in Fragment's root view. Is this a bug?

Nikiole91
  • 344
  • 2
  • 10
Christine
  • 79
  • 2
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your code and accurately describe the problem. Specifically, *how* is it "not working"? – Prune Jan 27 '16 at 22:41

1 Answers1

0

Try replacing edSmsCode with (EditText)getCurrentFocus() (get the view that's being focused, in this case an editText) in the afterTextChanged() method.

public void afterTextChanged(Editable s) {
   EditText editText = (EditText)getCurrentFocus();
   String str = editText.getText().toString();
   if (str.length() == 3 && len < str.length()) { 
      editText.append("-");
   }
}

source: https://stackoverflow.com/a/5951792/5837758

If that doesn't solve it, you can also try setting edSmsCode as final, according to this answer: https://stackoverflow.com/a/27094374/5837758

Community
  • 1
  • 1
Nikiole91
  • 344
  • 2
  • 10