java - 从内部类获取外部类变量(局部变量)

标签 java android listview

我试图找出一种将 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/

相关文章:

java - 如何从另一个类访问对象(例如 ArrayList)?

android - MediatorLiveData源在测试期间不会更新

android - 带有 webview 项目的 ListView 适合新闻应用程序吗?

android - 如何将多个项目放在 ListView 的同一行?

android - 在android中更改 ListView 内文本的颜色

Java 对象初始化 - 什么时候需要?

Java - 有没有办法在扫描 ArrayList 中的整数时中断 while 循环而不给出无效输入?

java - 在 AsyncTask 执行方法中传递单选按钮代码

java - 如何在Java中设置从串行端口读取时的超时?

java - Slick util 错误与 png [含解决方案]