Android:listview中的Checkbox(如何在Adapter中创建OnCheckedChangeListener)

时间:2017-08-20 10:14:17

标签: java android listview checkbox adapter

我正在创建一个待办事项列表应用程序,我有一个关于在列表适配器中使用复选框及其侦听器的问题。我在listview中的单行包含三个TextView和一个Checkbox。我想在用户"检查"时更改单行背景复选框。我已经读过我应该将复选框监听器放在我的适配器类中,所以我做到了。现在是问题了 - 当我在listview中添加几行并且未选中所有这些复选框时,一切正常,但是当我添加一行时,选中复选框并尝试添加另一行我收到错误

  

java.lang.NullPointerException:尝试调用虚方法' void android.view.View.setBackgroundColor(int)'在空对象引用上

以下是我的适配器的代码。谢谢你的任何建议。我刚开始使用Android编程,所以感谢您提前了解。

public class ToDoAdapter extends ArrayAdapter<ToDoTask> {


ArrayList<ToDoTask> objects;
Context context;
int resource;

public ToDoAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<ToDoTask> objects) {
    super(context, resource, objects);
    this.objects = objects;
    this.context = context;
    this.resource = resource;
}

@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
    View view = convertView;
    ToDoHolder toDoHolder = null;

    if (view == null) {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.row, parent, false);

        toDoHolder = new ToDoHolder();
        toDoHolder.rowTitle = (TextView) view.findViewById(R.id.rowTitle);
        toDoHolder.rowDesc = (TextView) view.findViewById(R.id.rowDesc);
        toDoHolder.rowDate = (TextView) view.findViewById(R.id.rowDate);
        toDoHolder.rowIsDone = (CheckBox) view.findViewById(R.id.rowCheckBoxDone);

        toDoHolder.rowIsDone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if(checked){
                    parent.getChildAt(position).setBackgroundColor(Color.parseColor("#8FE370"));
                }
                else
                    parent.getChildAt(position).setBackgroundColor(Color.WHITE);
            }
        });

        view.setTag(toDoHolder);
    } else {
        toDoHolder = (ToDoHolder) view.getTag();
    }

    ToDoTask object = objects.get(position);
    toDoHolder.rowTitle.setText(object.getTitle());
    toDoHolder.rowDesc.setText(object.getDescription());
    toDoHolder.rowDate.setText(object.getDate());
    toDoHolder.rowIsDone.setChecked(object.getDone());

    return view;
}

static class ToDoHolder {
    TextView rowTitle;
    TextView rowDesc;
    TextView rowDate;
    CheckBox rowIsDone;
}
}

下面是我的MainActivity类,它从&#34; AddToDoTask&#34;获取单行元素的详细信息。类。

public class MainActivity extends AppCompatActivity {
private final int requestCode = 1;
ArrayList<ToDoTask> lista = new ArrayList<>();
ToDoAdapter adapter = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.buttonAdd);
    ListView listView = (ListView) findViewById(R.id.listView);

    adapter = new ToDoAdapter(this, R.layout.row, lista);
    listView.setAdapter(adapter);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), AddToDoTask.class);
            startActivityForResult(intent, requestCode);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    String title, description, date;
    Boolean isDone;

    if (requestCode == 1) {
        if (null != data) {
            title = data.getStringExtra("title");
            description = data.getStringExtra("description");
            date = data.getStringExtra("date");
            isDone = data.getBooleanExtra("done", false);

            lista.add(new ToDoTask(title, description, date, isDone));
            adapter.notifyDataSetChanged();
        }
    }
}

} enter image description here

2 个答案:

答案 0 :(得分:1)

public class ToDoAdapter extends ArrayAdapter<ToDoTask> {
    private ArrayList<ToDoTask> objects;
    private Context context;
    private int resource;
    private SparseBooleanArray checkedPositions = new SparseBooleanArray();

    public ToDoAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<ToDoTask> objects) {
        super(context, resource, objects);
        this.objects = objects;
        this.context = context;
        this.resource = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ToDoHolder toDoHolder;
        if (convertView == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView = layoutInflater.inflate(R.layout.row, parent, false);
            toDoHolder = new ToDoHolder();
            toDoHolder.rowTitle = (TextView) convertView.findViewById(R.id.rowTitle);
            toDoHolder.rowDesc = (TextView) convertView.findViewById(R.id.rowDesc);
            toDoHolder.rowDate = (TextView) convertView.findViewById(R.id.rowDate);
            toDoHolder.rowIsDone = (CheckBox) convertView.findViewById(R.id.rowCheckBoxDone);
            convertView.setTag(toDoHolder);
        } else {
            toDoHolder = (ToDoHolder) convertView.getTag();
        }
        toDoHolder.rowTitle.setTag(position);
        toDoHolder.rowIsDone.setTag(convertView);
        toDoHolder.rowIsDone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                View view = (View) compoundButton.getTag();
                TextView title = (TextView) view.findViewById(R.id.rowTitle);
                int pos = (int) title.getTag();
                if (checked) {
                    checkedPositions.put(pos, true);
                    view.setBackgroundColor(Color.parseColor("#8FE370"));
                } else {
                    checkedPositions.put(pos, false);
                    view.setBackgroundColor(Color.WHITE);
                }
            }
        });
        ToDoTask object = objects.get(position);
        toDoHolder.rowTitle.setText(object.getTitle());
        toDoHolder.rowDesc.setText(object.getDescription());
        toDoHolder.rowDate.setText(object.getDate());
        toDoHolder.rowIsDone.setChecked(object.getDone() || checkedPositions.get(position));
        return convertView;
    }

    private class ToDoHolder {
        private TextView rowTitle;
        private TextView rowDesc;
        private TextView rowDate;
        private CheckBox rowIsDone;
    }
}

答案 1 :(得分:0)

您必须在row xml文件中添加布局,并将布局放在toDoHolder中,只需更改布局背景颜色即可。您可以访问

等子视图
layout.findViewByID(int ID);