我是Android新手......我開發了一個應用程序,通過單擊按鈕來轉換圖像,並添加Handler Runnable以自動獲取圖像轉換(也可以在未按下按鈕時),延遲時間爲5000ms。但我必須在此時按下按鈕停止處理程序,因爲某些原因我無法執行此操作。如何停止postnlay中的Runnable Handler
public class MainActivity extends AppCompatActivity {
private Integer images[]={R.drawable.pic1, R.drawable.pic21, ....
public int currImage=0;
public int ThreadCnt = 0;
public boolean backInt=true,forwardInc=false, ThreadInc=true;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
initializeImageSwitcher();
setInitialImage();
setImageRotateListener();
final Handler handler = new Handler();
final Runnable run = new Runnable() {
@Override
public void run() {
//forwardInc is a Boolean indicating that click button occurred
if(forwardInc){
//and in this case (of forwardInc=true) I want to stop runnable for 5sec
handler.removeCallbacks(this);
handler.postDelayed(this, 5000);
forwardInc=false;
setInitialImage();
setImageRotateListener();
currImage++;
ThreadCnt++;
}
handler.postDelayed(this, 5000);
}
};
handler.post(run);
,這是該按鈕的代碼單擊
public void setImageRotateListener() {
final Button rotatebutton=(Button) findViewById(R.id.btnRotateImage);
rotatebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currImage++;
//forwardInc indicating that click button occurred
forwardInc=true;
...
setCurrentImage();
...
呼叫'handler.removeCallbacks(運行)'取消那個'Runnable'。 – CommonsWare
但我已經將它添加到run()方法中的if語句中。 handler.removeCallbacks(本); –
@CommonsWare,但我已經將它添加到run()方法中的if語句中。 'handler.removeCallbacks(本);' –