2014-05-19 214 views
0

我使用此代碼,以便當我按下我的播放按鈕時,它將更改爲停止按鈕。當我在顯示停止按鈕時按下它時,如何將其更改回播放按鈕?Android更改播放按鈕停止並停止播放按鈕

final ImageView Play_button = (ImageView)findViewById(R.id.playbutton); 



      Play_button.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) { 

       Play_button.setImageResource(R.drawable.stopicon); 

      } 
      }); 

回答

1

這是一件非常簡單的事情。在一些地方保存你按鈕的狀態:

boolean isPlay = true; 

final ImageView playButton = (ImageView) findViewById(R.id.playbutton); 
playButton.setOnClickListener(new OnClickListener() { 

    public void onClick(View v) { 
     if(isPlay) 
      playButton.setImageResource(R.drawable.stopicon); 
     else 
      playButton.setImageResource(R.drawable.playicon); 
     isPlay = !isPlay; 
    } 

}); 
+0

我得到這個錯誤:「不能指非final的變量isPlay在不同的方法定義的內部類中」 – user1300788

+0

@ user1300788定義'布爾isPlay = true'作爲類成員。 – Onik

+0

哦,對不起。 'isPlay'必須是一個字段(在方法外聲明)或者是final。選擇你想要的。 –

2

您需要在這種情況下使用if ... else條件,我也建議你使用boolean變量來檢查,如果是打還是不(如果你正在使用媒體播放器,那麼你也可以使用媒體播放器類的isPlaying()方法)。但爲了方便,我會建議下面的技術。

final ImageView Play_button = (ImageView)findViewById(R.id.playbutton); 
boolean isPlaying = false; 


     Play_button.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      if(isPlaying){ 

       //You can add you code to change the icon to stop mode 
       //and finally set the flag to false as it has stopped now 
       isPlaying = false; 

      }else { 
       //Add you code here to change the icon back to play mode 
       //and finally set the flag to true as it will be playing now. 
       isPlaying = true; 
      } 
     } 
     }); 
2

簡單地使用標誌是這樣的:

final ImageView Play_button = (ImageView)findViewById(R.id.playbutton); 
boolean isPlayIcon = true; 

     Play_button.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      if(isPlayIcon){ 
       Play_button.setImageResource(R.drawable.stopicon); 
       isPlayIcon = false; 
      }esle{ 
      Play_button.setImageResource(R.drawable.playicon); 
      isPlayIcon = true; 
      } 

     } 
     });