将自定义CheckBox添加到ListView

时间:2012-05-24 08:14:19

标签: android checkbox adapter

我在getView()(PlanAdapter类)中添加了新的CheckBox

public View getView(int position, View convertView, ViewGroup viewGroup) {
        Plan entry = listPlan.get(position);

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.walkRow, null, false);

        }
        LinearLayout d = (LinearLayout)convertView.findViewById(R.id.checkBoxPlace);


        TextView distance = (TextView) convertView.findViewById(R.id.distance);
        distance.setText(" " + entry.getexerciseNumber());

        TextView time = (TextView) convertView.findViewById(R.id.time);
        time.setText(" " + entry.getwholeTime());

        CheckBox chckStart = new CheckBox(context);
        chckStart = entry.getCheckBox();
        chckStart.setFocusable(false);
        d.addView(chckStart); //here i get force close
        return convertView;
    }

当我向下滚动它看起来很好,但是当我向后滚动并向上滚动它时会崩溃。

计划类中的getter,setter

public CheckBox getCheckBox(){
        return checkBox;
    }

    public void setCheckBox(CheckBox checkBox){
        this.checkBox = checkBox;
    }

和Main class中的checkBox

    for (byte i = 0; i < db.planView.size(); i++) {
        chcBox = new CheckBox(this);
        chcBox.setId(i);
        checkboxList.add(chcBox);

        listOfPlan.add(new Plan(db.planView.get(i).getText().toString(), db
                .count(db.planView.get(i).getText().toString(),
                        getApplicationContext()), chcBox));

    }

日志:http://wklej.to/RpBvr/html

1 个答案:

答案 0 :(得分:2)

您正尝试将每个复选框添加到多个父视图中,这是您无法做到的...

然而,ListView已经有很多功能来实现复选框,这里有一种方法:

public class Example extends Activity implements OnItemClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String[] array = {"one", "two", "three"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, array);

        ListView listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        listView.setOnItemClickListener(this);
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.v("Example", "ItemClick: " + ((ListView) parent).getCheckedItemPosition());
    }
}

您只需传递自己的XML文件即可自定义布局。

<强>加成

每次显示一行时,您都会刷新entry数据并尝试添加复选框,这就是您可以向下滚动但不能向上滚动的原因。如果您想保留自定义适配器,只需检查该行是否已经初始化,然后再尝试添加相同的值。