5

I have a listview adapter that when I modify my TextView, I call notifyDataSetChanged() on addTextChangeListener() method. But my TextView lose the focus. How I can keep the focus, overriding the notifyDataSetChanged()?

I do that but didn't work

@Override
public void notifyDataSetChanged(){
    TextView txtCurrentFocus = (TextView) getCurrentFocus();
    super.notifyDataSetChanged();
    txtCurrentFocus.requestFocus();
}
Artem Mostyaev
  • 3,589
  • 10
  • 48
  • 55
Ezrou
  • 428
  • 5
  • 14

2 Answers2

1

You can extend ListView class and override requestLayout() method. That method is called, when ListView finish update and steal focus. So, at the end of this methos you can return focus to your TextView.

public class ExampleListView extends ListView {

    private ListViewListener mListener;

    public ExampleListView(Context context) {
        super(context);
    }

    public ExampleListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ExampleListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void requestLayout() {
        super.requestLayout();
        if (mListener != null) {
            mListener.onChangeFinished();
        }
    }

    public void setListener(ListViewListener listener) {
        mListener = listener;
    }

    public interface ListViewListener {
        void onChangeFinished();
    }
}

and set listener to this ListView

ExampleListView listView = (ExampleListView) view.findViewById(R.id.practice_exercises_list);
listView.setListener(new ExampleListView.ListViewListener() {
            @Override
            public void onChangeFinished() {
                txtCurrentFocus.requestFocus();
            }
        });
Artem Mostyaev
  • 3,589
  • 10
  • 48
  • 55
  • thats nice and all, but when doing this, i loose the position of the focus in an editText. Any advice how i could solve this problem? – glace Apr 19 '16 at 11:03
  • @glace You can remember text position by using [TextWatcher as suggested here](http://stackoverflow.com/a/15030172/1219012]) and restore that position using [setSelection](http://stackoverflow.com/questions/8035107/how-to-set-cursor-position-in-edittext) – Artem Mostyaev Apr 19 '16 at 11:16
  • How can i know on which EditText i shall use this when generated dynamically. Pls don't tell me that i have to use one TextWatcher for each EditText. It must be possible to use one TextWatcer for multiple EditTexts right? Otherwise i will need ~30 plus TextWatchers -.- – glace Apr 19 '16 at 13:07
0

I had same problem with EditText and RecyclerView using this line of code, for my RecyclerView's Adapter solved the problem.

 adapter.setHasStableIds(true);
Andronymous
  • 80
  • 1
  • 9