ボタンの背景が1秒後に動的に変化する単純なアプリケーションを開発しています。アプリ名にstopButtonBackgroundChangingのボタンがあります。ボタンをクリックすると、ボタンの背景の変更が停止しますが、2秒後にアプリが予期せず停止します。」この点で私を助けてください。また、以下のコードを参照してください。それが本当にやりたいことです。
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