我目前有一个自定义ArrayAdapter
,它使用xml布局文件并使用传入的ArrayList<>
Java对象进行填充。在布局中有一个我称之为setOnCheckedChangeListener
的开关。但是,在侦听器内部,我无法检索交换机来自列表中的位置,甚至是该行中的其他视图。要么对我合适。
我见过有人使用ViewHolder
,但我不确定这是否能帮助我做我想做的事。这是我的适配器代码。
public class AlarmAdapter extends ArrayAdapter<Alarm> {
Context context;
TextView alarmId;
TextView repeatDaysText;
public AlarmAdapter(Context context, ArrayList<Alarm> alarmList){
super(context, R.layout.alarm_layout, alarmList);
this.context =context;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
//Get the data item for this position
Alarm alarm = getItem(position);
//Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.alarm_layout, parent, false);
}
//sets the widgets to correspond to variables
//Set hidden id reference
alarmId = (TextView)convertView.findViewById(R.id.hidden_alarm_id);
alarmId.setText(String.valueOf(alarm.getId()));
//Set the time display string
TextView timeText = (TextView) convertView.findViewById(R.id.time_display_text);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
timeText.setText(sdf.format(alarm.getTime()));
//Set the days repeating on
repeatDaysText = (TextView)convertView.findViewById(R.id.repeat_days_text);
if(alarm.getClass() == RepeatingAlarm.class){
String repeatText = UtilityFunctions.generateRepeatText(((RepeatingAlarm)alarm).getRepeatDays());
if(repeatText != null){
repeatDaysText.setText(repeatText);
repeatDaysText.setVisibility(View.VISIBLE);
}
} else {
repeatDaysText.setVisibility(View.GONE);
}
//Set the status of the alarm
Switch statusSwitch = (Switch) convertView.findViewById(R.id.activate_alarm_switch);
statusSwitch.setChecked(alarm.getStatus());
statusSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
//Activate alarm
// AlarmController.getInstance().activateAlarm(context,/*some id*/);
} else{
//Deactivate alarm
// AlarmController.getInstance().cancelAlarm(context,/*some id*/);
}
}
});
return convertView;
}
}
答案 0 :(得分:0)
ListView mListView = findViewById(R.id.listView);
for (int position = 0; position <mListView.getChildCount();position ++){
cb = (CheckBox) mListView.getChildAt(position ).findViewById(R.id.myCheckBox);
if(cb.isChecked()){
// doSomething with the position
}
答案 1 :(得分:0)
我能够利用Alarm checkedAlarm = getItem(position);
获取我的警报对象,然后从那里检索控制器所需的警报ID。我在on checked listener