0
我有一個ListView,每個ListView項有一個Switch小部件,我遇到的問題是當我在ArrayAdapter中設置值setOnCheckedChangeListener get觸發時。如何在不觸發setOnCheckedChangeListener的情況下在適配器中設置值?我發現了另一個類似的問題here,但這不適用於我。以下是我的ArrayAdapter代碼。開關小部件 - onCheckedChanged在ArrayAdapter中設置值時觸發
public class AlarmsAdapter extends ArrayAdapter<Alarms> {
private List<Alarms> alarmsList;
private Context context;
private ContactDetailsFragment cdFragment;
public AlarmsAdapter(Context context, int textViewResourceId, List<Alarms> alarms) {
super(context, textViewResourceId, objects);
this.context=context;
alarmsList=alarms;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Alarms alarm = alarmsList.get(position);
View view = convertView;
ViewHolder holder = null;
if(view == null) {
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.alarm_row, null);
holder = new ViewHolder();
holder.alarmLabel = (TextView) view.findViewById(R.id.alarmLabel);
holder.alarmDate = (TextView) view.findViewById(R.id.alarmDate);
holder.alarmTime = (TextView) view.findViewById(R.id.alarmTime);
holder.alarmEnabled = (Switch) view.findViewById(R.id.alarmEnabled);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
if(alarm != null) {
int alarmId = alarm.getAlarmDay();
holder.alarmLabel.setText(String.valueOf(alarmId));
// Alarm Date Time
long mDateTime = alarm.getAlarmTime();
Date nDate = new Date(mDateTime);
DateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy");
DateFormat timeFormat = new SimpleDateFormat("hh:mm a");
holder.alarmDate.setText(dateFormat.format(nDate));
holder.alarmTime.setText(timeFormat.format(nDate));
holder.alarmEnabled.setChecked((alarm.getIsOn() == 1) ? true : false);
holder.alarmEnabled.setTag(alarm.get_uid());
holder.alarmEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
alarm.setIsOn((isChecked) ? 1:0);
cdFragment.addCanceledAlarm(alarm);
}
});
}
return view;
}
class ViewHolder {
TextView alarmLabel;
TextView alarmDate;
TextView alarmTime;
Switch alarmEnabled;
}
public void setCdFragment(ContactDetailsFragment cdFragment) {
this.cdFragment = cdFragment;
}
}
謝謝@vasart,我使用了第一個選項,它解決了我的問題。 – Byron 2014-09-11 15:09:16