我想构建一个自定义数组适配器,每个列表项中都有两个复选框。当一个复选框被点击时,我想取消选中其他复选框,如果它被选中。所以,既不选中复选框,或只是其中之一。列表项中的多个复选框android
我认为我遇到的问题是我不清楚如何引用onClickListener中的其他复选框。这里是我的代码迄今:
public class PetWalkerAdapter extends ArrayAdapter{
protected Context mContext;
protected List mPets;
public PetWalkerAdapter(Context context, List pets) {
super(context, R.layout.pet_walker_item, pets);
mContext = context;
mPets = pets;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.pet_walker_item, null);
holder = new ViewHolder();
holder.petPictureView = (ImageView) convertView.findViewById(R.id.petPicture);
holder.petNameLabel = (TextView) convertView.findViewById(R.id.petNameLabel);
holder.ownerCheckBox = (CheckBox) convertView.findViewById(R.id.ownerCheckBox);
holder.walkerCheckBox = (CheckBox) convertView.findViewById(R.id.walkerCheckBox);
convertView.setTag(holder);
// If owner check is toggled, uncheck walker
holder.ownerCheckBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
ViewHolder petHolder = (ViewHolder) cb.getTag();
// Here's where the app crashes,
if (petHolder.walkerCheckBox.isChecked()) {
petHolder.walkerCheckBox.setChecked(false);
}
}
});
}
else {
holder = (ViewHolder)convertView.getTag();
}
ParseObject pet = mPets.get(position);
holder.petNameLabel.setText(pet.getString(ParseConstants.KEY_PET_NAME));
return convertView;
}
private static class ViewHolder {
ImageView petPictureView;
TextView petNameLabel;
CheckBox ownerCheckBox;
CheckBox walkerCheckBox;
}
public void refill(List pets) {
mPets.clear();
mPets.addAll(pets);
notifyDataSetChanged();
}
}
这里的logcat的
10-02 01:53:16.412 1270-1270/com.base8.wlkr E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.base8.wlkr, PID: 1270
java.lang.NullPointerException
at com.base8.wlkr.adapters.PetWalkerAdapter$1.onClick(PetWalkerAdapter.java:50)
at android.view.View.performClick(View.java:4438)
at android.widget.CompoundButton.performClick(CompoundButton.java:100)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
请让我知道如果你需要任何更多的信息。任何批评或引用赞赏。感谢您的期待。
2014-09-29
backlunp
+0
请把崩溃的logcat。 –
2014-09-29 21:49:05
+0
你考虑过单选按钮吗? –
2014-09-29 21:53:55
+0
@AndrewMedico我没有想过单选按钮,我的目标是循环遍历列表,并查看用户在另一个片段中点击** Save **按钮时选中的选项(如果有的话)。如果我无法得到这个工作,我可能会考虑修改,谢谢你的建议! –
2014-10-02 01:59:37