[英]Get Outer Class Variable From Inner Class (local variable)
I am trying to figure out a way for the position variable from the getView()
method to be passed to the inner class. 我正在尝试从getView()
方法中将位置变量传递给内部类的方法。 However this can't be a final variable because getView()
gets called for each item in the ListView
and hence it changes. 但是,这不能成为最终变量,因为ListView
每个项目都会调用getView()
,因此它会发生变化。 Is there a way to access that position variable without having it be final? 有没有一种方法可以访问该位置变量而无需使其最终确定? or making it final in a clever way that would make something like this work? 还是以一种巧妙的方式使其最终定稿,从而使类似的工作得以完成? Here is my code 这是我的代码
public class AlarmListAdapter extends ArrayAdapter<Alarm> {
public AlarmListAdapter(Context context, int resource, List<Alarm> alarms) {
super(context, resource, alarms);
}
@Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
LayoutInflater viewInflator = LayoutInflater.from(getContext());
view = viewInflator.inflate(R.layout.item_alarm_list, null);
}
Alarm alarm = getItem(position);
if (alarm != null) {
TextView alarmName = (TextView) view
.findViewById(R.id.alarm_list_item_name);
TextView alarmTime = (TextView) view
.findViewById(R.id.alarm_list_item_time);
Switch status = (Switch) view
.findViewById(R.id.alarm_list_item_status);
alarmName.setText(alarm.getName());
alarmTime.setText(alarm.getFormattedHour() + ":"
+ alarm.getMinute() + " " + alarm.getAMPM());
status.setChecked(alarm.getOn());
status.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Alarm alarm = getItem(position);
} else {
// The toggle is disabled
}
}
});
}
return view;
}
}
If you make the position
variable final, it will be OK. 如果将position
变量设为final,则可以。 You're using it as a read only variable. 您正在将其用作只读变量。 Also making it final has no effect on the caller, only on the body of your method you won't be allowed to change it. 将其设置为final不会对调用方产生任何影响,仅对方法的主体无效,不允许您对其进行更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.