我有一个带有 EditText 的列表项,我不知道会有多少项。 我在 EditText 中输入一些文本,然后向下滚动 ListView 时遇到问题,再次向上滚动后,我的第一个 EditText 中没有文本,或者 ListView 中的其他 EditText 中有一些文本。
我试过 TextWatcher,并将数据保存到数组,但问题是 ListView 中返回的 View 位置并不总是正确的,所以我从数组中丢失了一些数据。 -.-
如何检测 ListView 中 View 的正确位置?
例如:
如果我在 ListView 中有 10 个项目,并且当前只有 5 个是可见的。 适配器返回位置从 0 到 4……没问题。 当我向下滚动时,第 6 项的位置是 0...wtf?我丢失了位置 0 上数组的数据 :)
我正在使用 ArrayAdapter。
请帮忙。
这是一些代码:
public View getView(int position, View convertView, ViewGroup parent) {
tmp_position = position;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.element_in_game, null);
holder.scoreToUpdate = (EditText) convertView
.findViewById(R.id.elementUpdateScore);
holder.scoreToUpdate.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
scoresToUpdate[tmp_position] = s.toString();
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
initScoresToUpdateEditTexts(holder.scoreToUpdate, hint);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.scoreToUpdate.setText(scoresToUpdate[tmp_position]);
}
return convertView;
}
最佳答案
你应该尝试如下方式:
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.element_in_game, null);
holder.scoreToUpdate = (EditText) convertView
.findViewById(R.id.elementUpdateScore);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//binding data from array list
holder.scoreToUpdate.setText(scoresToUpdate[position]);
holder.scoreToUpdate.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
//setting data to array, when changed
scoresToUpdate[position] = s.toString();
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
return convertView;
}
解释: ListView 的回收行为,实际上是清除所有与其Row Item 绑定(bind)的数据,当超出视野时。 因此,从您需要再次绑定(bind)数据的任何方向进入视野的每一行。 此外,当 EditText 文本更改时,您还必须在某些数据结构中保留值,因此稍后再次行数据绑定(bind)您可以提取位置数据。 您可以使用数组 ArrayList 来保存 edittext 数据,也可以用来绑定(bind)数据。
在 Recyclerview Adapter 中使用类似的行为,您需要了解适配器行数据的数据绑定(bind)背后的逻辑。
关于android - EditText 在 ListView 中滚动时丢失内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8772714/