为什么android图像会在两次后停止变化?

时间:2016-11-08 15:26:48

标签: android xml-drawable

愚蠢的noob问题,但希望有人能够帮助你! 我正试图在按下按钮时改变两个源之间的图像。两个图像存储在可绘制的称为pic1和pic2中。但运行代码会导致图片更改两次,然后不再进一步更改。有人可以解释一下吗?

以下是代码:

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

1 个答案:

答案 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

        }
    });

尝试并让我知道会发生什么