Java 从内部类获取外部类变量(局部变量)
我试图找出一种方法,将Java 从内部类获取外部类变量(局部变量),java,android,listview,Java,Android,Listview,我试图找出一种方法,将getView()方法中的position变量传递给内部类。但是,这不能是最终变量,因为getView()会为ListView中的每个项目调用,因此它会发生变化。有没有一种方法可以访问该位置变量而不必将其作为最终变量?或者以一种聪明的方式使它成为最终版本,从而使类似的东西发挥作用?这是我的密码 public class AlarmListAdapter extends ArrayAdapter<Alarm> { public AlarmListAda
getView()
方法中的position变量传递给内部类。但是,这不能是最终变量,因为getView()
会为ListView
中的每个项目调用,因此它会发生变化。有没有一种方法可以访问该位置变量而不必将其作为最终变量?或者以一种聪明的方式使它成为最终版本,从而使类似的东西发挥作用?这是我的密码
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;
}
}
公共类AlarmListAdapter扩展了ArrayAdapter{
公共AlarmListAdapter(上下文上下文、int资源、列表报警){
超级(上下文、资源、警报);
}
@凌驾
公共视图getView(内部位置、视图视图、视图组父视图){
如果(视图==null){
LayoutInflater viewInflator=LayoutInflater.from(getContext());
视图=视图充气器。充气(R.layout.item\u alarm\u list,空);
}
报警=获取项目(位置);
如果(报警!=null){
TextView alarmName=(TextView)视图
.findViewById(R.id.报警列表项目名称);
TextView alarmTime=(TextView)视图
.findViewById(R.id.报警列表项目时间);
开关状态=(开关)视图
.findViewById(R.id.报警列表项目状态);
alarmName.setText(alarm.getName());
alarmTime.setText(alarm.getFormattedHour()+“:”
+alarm.getMinute()+“”+alarm.getAMPM());
status.setChecked(alarm.getOn());
status.setOnCheckedChangeListener(新建CompoundButton.OnCheckedChangeListener(){
检查更改后的公共无效(复合按钮视图,布尔值已检查){
如果(已检查){
报警=获取项目(位置);
}否则{
//切换被禁用
}
}
});
}
返回视图;
}
}
如果将位置设置为final,则该变量将正常。您正在将其用作只读变量。
另外,将其设置为final对调用方没有影响,只对方法体有影响,不允许您更改它 检查这个:谢谢,这正是我要找的。