Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep focus on TextView after notifyDatasetChanged() was called on custom listview?

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();
}
like image 762
Ezrou Avatar asked Oct 22 '13 10:10

Ezrou


1 Answers

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();
            }
        });
like image 50
Artem Mostyaev Avatar answered Oct 05 '22 13:10

Artem Mostyaev