我正在尝试使用ImageView
创建一个可切换的开/关按钮,但图像将永远改变。
这是我的代码:
public void toggleBtn(View v) {
ImageView btn = (ImageView) v;
if (state) { // "state" is a variable that switches with the button
btn.setImageDrawable(getResources().getDrawable(R.drawable.pwbtn_off));
state = !state;
} else {
btn.setImageDrawable(getResources().getDrawable(R.drawable.pwbtn_on));
state = !state;
}
}
图像更改后的代码在图像更改之前运行(我假设更改是异步的)但两个图像都只是 52KB 所以我怀疑加载图像需要这么长时间。
有更有效的方法吗?
答案 0 :(得分:0)
您可能需要invalidate视图来强制操作系统更新布局。
public void toggleBtn(View v) {
ImageView btn = (ImageView) v;
if (state) { // "state" is a variable that switches with the button
btn.setImageDrawable(getResources().getDrawable(R.drawable.pwbtn_off));
state = !state;
} else {
btn.setImageDrawable(getResources().getDrawable(R.drawable.pwbtn_on));
state = !state;
}
v.invalidate();
}