[英]Fragment ListView with Checkbox strange behavior
I have a ListView
with Checkbox
inside a Fragment
that extends FragmentList
. 我有一个Fragment
内部扩展了FragmentList
Checkbox
的ListView
。 The strange behavior is multiple items get checked when one item is clicked. 奇怪的行为是单击一个项目时会检查多个项目。 Strangely, when the list is scrolled, some item gets automatically selected or deselected and I have no ScrollListener
set. 奇怪的是,滚动列表时,某些项目会自动被选择或取消选择,而我没有设置ScrollListener
。
Here's the code : 这是代码:
@Override
public void onStart() {
super.onStart();
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.chk);
if (mCheckBox.isChecked()) {
mCheckBox.setChecked(false);
getListView().setItemChecked(i, false);
} else {
mCheckBox.setChecked(true);
getListView().setItemChecked(i, true);
}
mCallback.onArticleSelected(i, isChoice);
}
});
}
Required: image http://windrealm.org/tutorials/android/planets-fragmentactivity.png 必填: 图片http://windrealm.org/tutorials/android/planets-fragmentactivity.png
ListView
's items recycle while you are scrolling. 滚动时, ListView
的项目会回收。 You should put a boolean
parameter (isChecked) to your ListView
row object then in your getView method u should initialize your CheckBox
with that boolean
parameter. 您应该将一个boolean
参数(isChecked)放入ListView
行对象,然后在getView方法中,您应该使用该boolean
参数初始化CheckBox
。 For example: 例如:
Assume that your row object: 假设您的行对象:
public class Trial{
public String title;
public boolean isChecked;
}
In your ListView
adapter's getView method, you should check isChecked
parameter of your object: 在ListView
适配器的getView方法中,应检查对象的isChecked
参数:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View view = inflater.inflate(R.layout.your_listview_item, parent, false);
Trial item = items.get(position);
yourHolder.checkBox = (CheckBox) view.findViewById(R.id.chk);
yourHolder.checkBox.setChecked(item.isChecked);
return view;
}
Good luck. 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.