EditText in Listview loses focus when pressed on Android 4.x

A classic hack for situations like this is to use a handler and postDelayed(). In your adapter:

private int lastFocussedPosition = -1;
private Handler handler = new Handler();

public View getView(final int position, View convertView, ViewGroup parent) {

    // ...

    edittext.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                handler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (lastFocussedPosition == -1 || lastFocussedPosition == position) {
                            lastFocussedPosition = position;
                            edittext.requestFocus();
                        }
                    }
                }, 200);

            } else {
                lastFocussedPosition = -1;
            }
        }
    });

    return convertView;
}

This works on my device, but keep this code out of production. I also wouldn’t be surprised if the focus bug manifests itself differently in different android versions or roms.

There are also many other problems with embedding an EditText within a ListView that have solutions that feel like a hack. See all of the other people struggling.

It’s also very easy to have something like this happen:

like this.

After having gone down similar paths many times myself, I’ve mostly given up on trying to override any of the default keyboard behaviours or quirks. I would recommend trying to find alternative solution in your app if possible.

Have you considered having the ListView rows be just a styled TextView and then displaying a Dialog with an EditText when a row is clicked, updating the TextView as necessary?

Leave a Comment