以下是代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button changeBtn = (Button) findViewById(R.id.buttonChange);
final ImageView image = (ImageView) findViewById(R.id.image1);
final Drawable current = image.getDrawable(); //this is pic1
changeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(image.getDrawable()==current) //if pic1
image.setImageResource(R.drawable.pic2);
else image.setImageResource(R.drawable.pic1);
}
});
答案 0 :(得分:0)
因为您没有更新当前和变量是最终的。 在java中,您无法更改最终变量see here。 只需声明那些变量default或public,并在onClick方法中更新当前变量
Button changeBtn;
ImageView image;
Drawable current;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changeBtn = (Button) findViewById(R.id.buttonChange);
image = (ImageView) findViewById(R.id.image1);
current = image.getDrawable(); //this is pic1
changeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(image.getDrawable()==current) //if pic1
image.setImageResource(R.drawable.pic2);
else image.setImageResource(R.drawable.pic1);
current = image.getDrawable(); //this will update the current , you have to update the current because it change in the if/else condition
}
});
尝试并让我知道会发生什么