适用于Android滚动问题的ListView适配器

时间:2016-03-31 03:11:48

标签: java android listview

我为listview创建了一个适配器。对于每个列表项,它上面都有一个复选框。每当我滚动我的列表视图时,它会随机设置复选框以检查项目。

以下是我的getView方法

public View getView(int position, View convertView, final ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.list_equipment_search, null);

    TextView serialno = (TextView) vi.findViewById(R.id.txtSerialNo); // Serial No
    TextView unitno = (TextView) vi.findViewById(R.id.txtUnitNo); // Unit No
    CustomCheckBox chkEquipment = (CustomCheckBox) vi.findViewById(R.id.chkEquipment); // Select CheckBox


    final Equipment equipment = data.get(position);

    // Setting all values in listview
    serialno.setText(equipment.GetSerialNo());
    unitno.setText(equipment.GetUnitNo());
    if (Equipment.EquipmentInList(equipment, selected))
        chkEquipment.setChecked(true, false);


    chkEquipment.setOnCheckedChangeListener((EquipmentSearchActivity) context);


    return vi;
}

复选框上的代码更改为

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    int pos = ((ListView) findViewById(R.id.listEquipment)).getPositionForView(buttonView);

    if (pos != ListView.INVALID_POSITION) {
        Equipment e = equipmentList.get(pos);
        if (isChecked && !Equipment.EquipmentInList(e, SelectedEquipment))
            SelectedEquipment.add(e);
        else if (!isChecked)
            SelectedEquipment = Equipment.RemoveEquipmentFromList(e, SelectedEquipment);
    }

    Button btnStoreEquipment = (Button) findViewById(R.id.btnStoreEquipment);

    if (SelectedEquipment.size() > 0)
        btnStoreEquipment.setVisibility(View.VISIBLE);
    else
        btnStoreEquipment.setVisibility(View.INVISIBLE);
}

2 个答案:

答案 0 :(得分:1)

这是因为您的getView实施。滚动时,始终会调用getView,请注意,如果inflate layoutconvertview,则nullchkEquipment。会发生什么情况,您的original checkbox会被回收并用于其他项目。 所以当你调用

  

if(Equipment.EquipmentInList(设备,选中))           chkEquipment.setChecked(true,false);

您实际上是在引用class myclass { public: void getvalues(); myclass(); private: int count; }; myclass::myclass() { count = 100; } void myclass::getvalues() { int count; std::cout << count << std::endl; } int main() { myclass foo; foo.getvalues(); return 0; } 更改其原始状态。

您可以阅读ListViews and ViewHolder Pattern以供参考。

答案 1 :(得分:1)

试试这个..

msg = bus_service.receive_queue_message('taskqueue', peek_lock=False)
print(msg.body)