Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditText selection anchor

Tags:

android

I have a listview, where each row is an EditText, with some text. When I tap on a row, EditText gets the focus, displays the blinking cursor and the selection anchor (you know the blue/gray looking handles that you drag around to select a range of text).

The problem is that when I move from one row to another (edittext to another), without enterting new text, the selection anchor in the previous edittext remains visible for a while. I would like to hide this anchor immediately if the edittext doesn't have focus.

Any ideas?

ClearFocus Doesn't work

        editText.setOnFocusChangeListener(new OnFocusChangeListener() {             
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {

                } else {
                    editText.clearFocus();
                    //editText.clearComposingText();                        
                }
            }
        });

Screenshot

The Problem

like image 844
States Avatar asked Nov 03 '22 12:11

States


1 Answers

I finally got it! First of all, I removed focusability from the ListView. Then I wrote a custom OnFocusChangeListener that removes the selection from the view that looses the focus. This listener is applied to the views by a custom adapter (I wrapped ArrayAdapter, but you can as well wrap a SimpleCursorAdapter).

Attached is a demo (tested on an emulator with Eclair):

public class ListOfEditViews extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ListView list = new ListView(this);
        list.setAdapter(getAdapter());
        list.setFocusable(false);
        list.setFocusableInTouchMode(false);

        setContentView(list);
    }

    private ListAdapter getAdapter() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.edit_text, R.id.text) {

            @Override
            public View getView (int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                view.setFocusable(true);
                view.setFocusableInTouchMode(true);
                view.setOnFocusChangeListener(listener);
                return view;
            }
        };

        String words = "Lorem ipsum dolor sit amen";

        for (String word: words.split(" "))
            adapter.add(word);

        return adapter;
    }

    private OnFocusChangeListener listener = new OnFocusChangeListener() {

        public void onFocusChange(View view, boolean hasFocus) {
            view.dispatchWindowFocusChanged(hasFocus);
        }
    };
}
like image 198
Raffaele Avatar answered Nov 13 '22 19:11

Raffaele