我试图找出一种将 getView()
方法中的位置变量传递给内部类的方法。但是,这不能是最终变量,因为 ListView
中的每个项目都会调用 getView()
,因此它会发生变化。有没有办法访问该位置变量而不使其成为最终变量?或者以一种聪明的方式将其最终化,从而使类似的事情能够发挥作用?这是我的代码
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;
}
}
最佳答案
如果将position
变量设置为最终变量,那就没问题了。您将其用作只读变量。
此外,使其成为最终版本对调用者没有影响,仅对方法主体没有影响,您将不被允许更改它。
关于java - 从内部类获取外部类变量(局部变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22592208/