ImageView Button Toggle in Android

寵の児 提交于 2019-12-08 13:40:42

问题


I'm trying to make an ImageView button toggle when I click on it. I've got the below code:

    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;
            }
        }
    });

But for some reason button01 is underlined in red in Eclipse and it gives the error:

Cannot refer to a non-final variable button01 inside an inner class defined in a different method

Does anyone know why it's doing this and how to fix it?

Thanks


回答1:


Here is the working code:

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;
        }
    }
});



回答2:


Try this,

        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;
            }
        }
    });



回答3:


Try this, it worked for me. Here checkbox visibility is set to "Invisible"...! this code is inside a button 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
    }
}


来源:https://stackoverflow.com/questions/10438014/imageview-button-toggle-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!