繁体   English   中英

将自定义CheckBox添加到ListView

[英]Add custom CheckBox to ListView

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

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类的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/htmlhttp://wklej.to/RpBvr/html

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

但是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数据并尝试添加复选框,这就是您可以向下滚动而不是向上滚动的原因。 如果要保留自定义适配器,只需检查该行是否已初始化,然后再尝试添加相同的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM