如何查看列表视图中的哪个位置包含正在单击的复选框

时间:2015-03-02 22:42:58

标签: android android-listview android-checkbox

在我的应用程序中,我将一个ArrayList保存在一个类(ClassList)中,一个ListView使用一个自定义ArrayAdapter来保存这个ArrayList。 ArrayAdapter包含包含TextView和CheckBox的视图。这是在ArrayList中保存的类:

public class Assignment {
private String mTitle;
private String mDescription;
private Date mDateAssigned;
private Date mDateDue;
private boolean mCompleted;

public Assignment(String title, String description, Date dateAssigned,
        Date dateDue) {
    mTitle = title;
    mDescription = description;
    mDateAssigned = dateAssigned;
    mDateDue = dateDue;
}

这是我的自定义适配器:

public class AssignmentAdapter extends ArrayAdapter<Assignment> {

    private ArrayList<Assignment> mList;
    private TextView titleTextView;
    private CheckBox isCompletedCheck;
    private int mPosition;

    public AssignmentAdapter(Context context, int resource,
            int textViewResourceId, ArrayList<Assignment> objects) {
        super(context, resource, textViewResourceId, objects);
        mList = objects;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = getLayoutInflater().inflate(
                    R.layout.assignment_row, null);
        }

        titleTextView = (TextView) convertView
                .findViewById(R.id.assignment_text);
        titleTextView.setText(mList.get(position).getTitle());

        isCompletedCheck = (CheckBox) convertView
                .findViewById(R.id.is_completed_check);
        isCompletedCheck.setChecked(mList.get(position).isCompleted());

        isCompletedCheck.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // mPosition should be the position in the ListView, is not currently
                ClassList.getInstance(getApplicationContext()).getList()
                        .get(index).getAssignments().get(mPosition)
                        .setCompleted(isCompletedCheck.isChecked());


                updateDatabase();

            }
        });

        return convertView;

    }

    public CheckBox getCompletedCheck() {
        return isCompletedCheck;
    }

}

我希望AssignmentAdapter中的mPosition与ListI中的位置参数类似,与onItemClick()中的position参数类似。我需要这个位置来将mCompleted设置为用户输入的内容。

2 个答案:

答案 0 :(得分:0)

点击此链接:http://www.mysamplecode.com/2012/07/android-listview-checkbox-example.html

这解释了如何在列表视图中添加复选框。

答案 1 :(得分:0)

每次调用适配器onItemClickListener时,请尝试在ListView上使用onClickListener,而不是初始化新的getView。您将获得该位置以及单击视图以确保它是复选框。