Question

I am facing problem while setting focus in EdiText. Below is my EditText property.

              <EditText
                    android:id="@+id/gatekeeperDetailedtUnitNo"
                    android:layout_width="270dip"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/gatekeeperDetailtxtUnitNo"
                    android:layout_marginTop="10dip"
                    android:hint="@string/unit_number"
                    android:inputType="number"
                    android:maxLength="8"
                    android:lines="1" />

Now I have added '-' after 6 digits. For that I have implemented TextWatcher.

 edtUnitNo.addTextChangedListener(new TextWatcher() {

        /**
         * This method is used to change charSequence when user enter more
         * then 6 character.
         */
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if (count < 7) {
                if (s.toString().contains("-")) {
                    Log.e(TAG, "< 7 Called");
                    String[] st1;
                    st1 = s.toString().split("-");
                    String st2 = st1[0];
                    edtUnitNo.setText(st2);
                    edtUnitNo.requestFocus();
                    edtUnitNo.requestFocus(EditText.FOCUS_RIGHT);
                }
            }
            if (edtUnitNo.getText().toString().length() == 7) {
                Log.e(TAG, "== 7 Called");
                String s1 = edtUnitNo.getText().toString();
                String s2 = s1.substring(0, 6);
                char s3 = s.charAt(6);
                edtUnitNo.setText(s2 + "-" + s3);
            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        public void afterTextChanged(Editable s) {

        }
    });

Eg. My EditText value looks like "123456-7". I am facing issue when I have added 7 digits along with '-'. When I am trying to delete the last character '7', the focus come to the 0th position.

But I want to make focus at last deleted character position(after 6).

Was it helpful?

Solution

put edtUnitNo.setSelection(edtUnitNo.getText().length()); in afterTextChanged function ........

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top