2

当我单击它时,我正在尝试切换 ImageView 按钮。我有以下代码:

    ImageView button01 = (ImageView) findViewById(R.id.button01);
    button01.setOnClickListener(new OnClickListener() {
        int button01pos = 0;
        public void onClick(View v) {
            if (button01pos == 0) {
                button01.setImageResource(R.drawable.image01);
                button01pos = 1;
            } else if (button01pos == 1) {
                button01.setImageResource(R.drawable.image02);
                button01pos = 0;
            }
        }
    });

但由于某种原因 button01 在 Eclipse 中带有红色下划线,它给出了错误:

不能在不同方法中定义的内部类中引用非最终变量 button01

有谁知道它为什么这样做以及如何解决它?

谢谢

4

3 回答 3

7

这是工作代码:

final ImageView button01 = (ImageView) findViewById(R.id.button01);
button01.setOnClickListener(new OnClickListener() {
    int button01pos = 0;
    public void onClick(View v) {
        if (button01pos == 0) {
            button01.setImageResource(R.drawable.image01);
            button01pos = 1;
        } else if (button01pos == 1) {
            button01.setImageResource(R.drawable.image02);
            button01pos = 0;
        }
    }
});
于 2012-05-04T11:25:51.660 回答
0

试试这个,它对我有用。这里复选框可见性设置为“不可见”......!此代码在按钮 OnClickListener 内...!

@Override
public void onClick(View v) {

    ImageView iv_icon = (ImageView) findViewById(R.id.icon);

    CheckBox cb = (CheckBox) findViewById(R.id.cb);

    if (cb.isChecked()) {
        iv_icon.setImageResource(R.drawable.image01);
        cb.setChecked(false);
    } else if (!cb.isChecked()) {
        iv_icon.setImageResource(R.drawable.image02);
        cb.setChecked(true);
    } else {
        // Nothing happens
    }
}
于 2013-12-23T11:02:09.350 回答
0

尝试这个,

        int button01pos = 0;

        ImageView button01 = (ImageView) findViewById(R.id.button01);
        button01.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            if (button01pos == 0) {
                button01.setImageResource(R.drawable.image01);
                button01pos = 1;
            } else if (button01pos == 1) {
                button01.setImageResource(R.drawable.image02);
                button01pos = 0;
            }
        }
    });
于 2015-02-06T01:12:20.443 回答