在自定义列表视图中调用notifyDatasetChanged()后如何保持TextView的焦点?

6

我有一个ListView适配器,当我修改TextView时,我会在addTextChangeListener()方法中调用notifyDataSetChanged()。但是我的TextView失去了焦点。如何在覆盖notifyDataSetChanged()的情况下保持焦点?

我已经尝试过,但没有效果。

@Override
public void notifyDataSetChanged(){
    TextView txtCurrentFocus = (TextView) getCurrentFocus();
    super.notifyDataSetChanged();
    txtCurrentFocus.requestFocus();
}
2个回答

1
我曾遇到过使用 EditTextRecyclerView 时出现的同样问题。使用以下代码行,可以解决我的 RecyclerViewAdapter 问题。
 adapter.setHasStableIds(true);

1
你可以扩展ListView类并覆盖requestLayout()方法。当ListView完成更新并且窃取焦点时,会调用该方法。因此,在此方法的末尾,您可以将焦点返回到您的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();
    }
}

并将监听器设置到这个ListView

ExampleListView listView = (ExampleListView) view.findViewById(R.id.practice_exercises_list);
listView.setListener(new ExampleListView.ListViewListener() {
            @Override
            public void onChangeFinished() {
                txtCurrentFocus.requestFocus();
            }
        });

这很好,但在执行此操作时,我会失去editText中焦点的位置。您有什么建议可以解决这个问题吗? - glace
@glace 你可以使用TextWatcher来记住文本位置,并使用setSelection来恢复该位置。 - Artem Mostyaev
我如何知道在动态生成时应该在哪个EditText上使用它?请不要告诉我我必须为每个EditText使用一个TextWatcher。肯定可以为多个EditText使用一个TextWatcher,对吧?否则我将需要30多个TextWatchers -.- - glace

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接