2014-02-26 34 views
-1

我的項目中有一個切換按鈕,我想切換按鈕應該打開飛行模式,然後在5秒後自動關閉它。我發現了一個代碼,但我不知道如何修改它與一個切換按鈕的工作啓用飛行模式Onclick -Android

public void onClick(View v) { 
    // check current state first 
    boolean state = isAirplaneMode(); 
    // toggle the state 
    toggleAirplaneMode(state); 

    state = isAirplaneMode(); 
    // toggle the state 
    toggleAirplaneMode(state); 
    ser = new ServiceState(); 
    ser.setState(STATE_IN_SERVICE); 
} 

切換按鈕

toggle = (ToggleButton) findViewById(R.id.tglbtn1); 
toggle.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
     if (toggle.isChecked()) { 
      Toast.makeText(
        getApplicationContext(), 
        "toggle button enabled", 
        Toast.LENGTH_LONG).show(); 
     } else { 
      Toast.makeText(getApplicationContext(), 
        "toggle button disabled", Toast.LENGTH_LONG).show(); 
     } 
    } 
}); 

} 
} 
+0

什麼**確實**不工作? – flx

回答

0

看看這個文件,它是關於ToggleButton管理在Android上: http://developer.android.com/guide/topics/ui/controls/togglebutton.html

可以幫助你瞭解它是如何工作的。

這就是說,如此快速地停用/重新激活飛行模式的目的是什麼?

秒鐘後執行任務,你可以使用Timer類: http://developer.android.com/reference/java/util/Timer.html

甚至更​​好: http://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html

0

我不知道究竟方法是幹什麼的,所以我在細節上猜測一點點。但你應該能夠填補空白:

public void onClick(View v) { 
    // check current state first 
    boolean state = isAirplaneMode(); 
    // toggle the state 
    toggleAirplaneMode(state); 

    state = isAirplaneMode(); 
    // toggle the state 
    toggleAirplaneMode(state); 
    ser = new ServiceState(); 
    ser.setState(STATE_IN_SERVICE); 

    // you might want to disable the button here 

    // change state back after 5s 
    new Handler().postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      // TODO actually change the state variable 
      // and toggle back the airplane mode 
      // if you disabled the button, enable it here 
     } 
    }, 5000); 
} 
+0

請檢查更新的問題 – Alienware

+0

您的集成問題是什麼?我的答案只是關於延遲的代碼執行。 – flx