ListView 中含有 EditText 导致焦点丢失的问题

时间:2022-09-20 08:40:55

ListView 中的 item 中有 EditText 时。

如果activity的输入法选项设置为 android:windowSoftInputMode="adjustResize"

当点击一个EditText弹出输入法时时,会导致界面layout变化,导致 listview 重新调用getView刷新界面,各个itemView的状态会被清除,导致当前点击的EditText的焦点丢失,导致无法输入。

解决方法: 记住当前hasFocus的Edit的position,在getView的时候重新设置focus。

 @Override
public View getView(int position, View convertView, ViewGroup parent) { Log.e("ss", "getView:" + position); View v = null;
ViewHolder vh = null;
if (convertView != null) {
v = convertView;
vh = (ViewHolder) v.getTag();
} else {
v = mInflater.inflate(R.layout.item, parent, false);
vh = new ViewHolder();
vh.infoTxt = (TextView) v.findViewById(R.id.info_txt);
vh.editTxt = (EditText) v.findViewById(R.id.edit_txt);
vh.editTxt.setOnFocusChangeListener(mListener);
v.setTag(vh);
} vh.editTxt.setTag(position);
vh.infoTxt.setText(position + ""); if (mFocusPosition == position) {
vh.editTxt.requestFocus();
} else {
vh.editTxt.clearFocus();
} return v;
} int mFocusPosition = -1; OnFocusChangeListener mListener = new OnFocusChangeListener() { @Override
public void onFocusChange(View v, boolean hasFocus) {
int position = (Integer) v.getTag();
if (hasFocus) {
mFocusPosition = position;
}
Log.e("test", "onFocusChange:" + position + " " + hasFocus);
}
};