我目前有一个自定义的ArrayAdapter,它使用xml布局文件,并使用传入的Java对象的ArrayList<>进行填充。在布局中有一个我称为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;
}
}发布于 2018-02-05 00:20:05
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
}发布于 2018-02-05 00:20:58
我能够利用Alarm checkedAlarm = getItem(position);来获取我的报警对象,然后从那里检索控制器所需的报警id。我把它称为on checked监听器中的第一件事
https://stackoverflow.com/questions/48610067
复制相似问题