【问题标题】:Keep focus on TextView after notifyDatasetChanged() was called on custom listview?在自定义列表视图上调用 notifyDatasetChanged() 后继续关注 TextView?
【发布时间】:2013-10-22 10:10:17
【问题描述】:

我有一个列表视图适配器,当我修改我的 TextView 时,我在 addTextChangeListener() 方法上调用 notifyDataSetChanged()。但是我的 TextView 失去了焦点。 我怎样才能保持焦点,覆盖notifyDataSetChanged()

我这样做了,但没有工作

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

【问题讨论】:

    标签: android listview android-arrayadapter notifydatasetchanged


    【解决方案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 您可以使用TextWatcher as suggested here 记住文本位置并使用setSelection 恢复该位置
    • 我如何知道动态生成时我应该在哪个 EditText 上使用它。请不要告诉我必须为每个 EditText 使用一个 TextWatcher。必须可以将一个 TextWatcer 用于多个 EditText 对吗?否则我将需要约 30 多个 TextWatchers -.-
    【解决方案2】:

    EditTextRecyclerView 我也有同样的问题 使用这行代码,我的RecyclerViewAdapter 解决了这个问题。

     adapter.setHasStableIds(true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多