嗨,我想实现一个长列表,其中用户可以检查列表中的项目view.when滚动列表项,然后我将检查的项目存储在sparseboolean数组,但是当我尝试通过点击一个按钮来检查哪些项目被选中。它显示奇怪的行为。当我检查第一个项目,然后单击按钮然后它给了正确的结果,但是当我开始检查从列表底部的项目。那么它显示出奇怪的行为。从0-13索引有14个项目。当我检查第13个元素时,它没有显示吐司。当我点击第12个元素时,它显示没有吐司。当我点击第12个元素时,它显示没有吐司第一次吐司出现时我点击第8元素。请帮助我找出我错在哪里,并帮助我修复bug。当我点击第7元素三敬酒来到7,8,9当我点击第6元素5toast出现6,7, 8,9,10。请帮助我解决这个bug。我想显示选中的烤面包中的数字。 这里是我的代码检查列表视图中检查的项目
/**
* This example shows how to create a list of checkboxes.
*/
public class CheckboxActivity extends ListActivity implements
AdapterView.OnItemClickListener {
static SparseBooleanArray mCheckStates;
private CheckBoxAdapter mCheckBoxAdapter;
List<Boolean> check;
Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCheckBoxAdapter = new CheckBoxAdapter(this,
R.layout.list_item_checkbox, GENRES);
setListAdapter(mCheckBoxAdapter);
check=new ArrayList<Boolean>();
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
for(int i=0;i<mCheckStates.size()+1;i++)
if(mCheckStates.get(i)==true)
Toast.makeText(CheckboxActivity.this,i+" " ,Toast.LENGTH_SHORT).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int
position, long id) {
mCheckBoxAdapter.toggle(position);
}
private static class CheckBoxAdapter extends ArrayAdapter<String>
implements CompoundButton.OnCheckedChangeListener {
public CheckBoxAdapter(Context context, int resource, String[]
objects) {
super(context, resource, objects);
mCheckStates = new SparseBooleanArray(objects.length);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final CheckBox view = (CheckBox) super.getView(position,
convertView, parent);
view.setTag(position);
view.setChecked(mCheckStates.get(position, false));
view.setOnCheckedChangeListener(this);
return view;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
private static final String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy",
"Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi",
"Television", "Thriller"
};
}
HUH ?!请考虑把你的段落分成几块。很难理解5行句子描述你的检查项目的流程。 – Jack
@Jack你好,我想现在我解释正确的问题,请帮助。 –
你有没有想过这个?我只是注意到,在你的for循环btn onClickListener,你是从i = 1,到mCheckStates.size()+ 1,我认为这应该只是mCheckStates.size() – Jack