2016-11-08 54 views
0

愚蠢noob問題,但希望有人善意幫助! 我試圖在按下按鈕時更改兩個源之間的圖像。兩個圖像存儲在可繪製的pic1和pic2中。但運行代碼會導致圖片更改兩次,然後不再進一步更改。有人可以解釋嗎?爲什麼android圖像兩次後停止更改?

下面是代碼:

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

因爲你不更新當前和變量是最終的。 在java中,您不能更改最終變量see here。 只需要聲明的變量默認或公衆和在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 

     } 
    }); 

嘗試更新當前的變化,讓我知道發生了什麼