0
我正在開發一個簡單的應用程序,其中按鈕背景會在一秒鐘後動態更改。我的應用程序名稱中有一個按鈕stopButtonBackgroundChanging,因爲我點擊按鈕它會停止更改按鈕背景,但在2秒後應用程序停止意外。「請在這方面幫助我,並在下面看到我的代碼可能會更好一些那什麼是我真正想要做的如何通過使用buttonStop停止可運行的Android
UpdateRunnable updateRunnable;
private Runnable mEndlessRunnable;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
Button stopButtonBackgroundChanging = (Button)findViewById(R.id.buttonStop);
stopButtonBackgroundChanging.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//See implementation of stop() method at the end of the code
updateRunnable.stop();
}
});
mEndlessRunnable = (Runnable) new UpdateRunnable(new Handler(), new Button[]
{
(Button) findViewById(R.id.button1),
(Button) findViewById(R.id.button2),
(Button) findViewById(R.id.button3),
(Button) findViewById(R.id.button4),
});
mEndlessRunnable.run();
}// End of onCreate()
//Start of UpdateRunnable
private static class UpdateRunnable implements Runnable
{
private boolean myContinue = true;
private Random mRand = new Random();
private Handler mHandler;
private Button[] mButtons;
private Button mCurButton;
private int mState;
public UpdateRunnable(Handler handler, Button[] buttons)
{
mHandler = handler;
mButtons = buttons;
}
public void run()
{
if(myContinue)
{
// select a button if one is not selected
if (mCurButton == null)
{
mCurButton = mButtons[mRand.nextInt(mButtons.length)];
}
// check internal state, `0` means first bg change, `1` means last
switch (mState)
{
case 0:
mCurButton.setBackgroundResource(R.drawable.buttonyellow);
mState = 1;
break;
case 1:
mCurButton.setBackgroundResource(R.drawable.buttonblue);
// reset state and nullify so this continues endlessly
mState = 0;
mCurButton = null;
break;
}
mHandler.postDelayed(this, 1000);
}
}// End of run()
public void stop()
{
this.myContinue =false;
}
}//End of class UpdateRunnable
歡迎vonRogue並感謝你的答案... –
@Von流氓你答案由gautham複製看到這個鏈接.http://stackoverflow.com/questions/16188398/how-to-stop-runnable-on-button-click-in-android –