【问题标题】:Add custom CheckBox to ListView将自定义 CheckBox 添加到 ListView
【发布时间】:2012-05-24 08:14:18
【问题描述】:

我在 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;
    }

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

Plan 类中的 getter、setter

public CheckBox getCheckBox(){
        return checkBox;
    }

    public void setCheckBox(CheckBox checkBox){
        this.checkBox = 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

【问题讨论】:

标签: android checkbox adapter


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多