在这里,按钮的背景每 4 秒后定期更改。在这里,您传递背景的 id 并检查它是否适合您。
希望这可以帮助 :)
public class MyActivity extends Activity {
private Runnable mEndlessRunnable;
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.my_activity);
mEndlessRunnable = new UpdateRunnable(new Handler(), new Button[] {
(Button) findViewById(R.id.button_1),
(Button) findViewById(R.id.button_2)
});
mEndlessRunnable.run();
}
private static class UpdateRunnable extends Runnable {
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() {
// 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.blue_bg);
mState = 1;
break;
case 1:
mCurButton.setBackgroundResource(R.drawable.yellow_bg);
// reset state and nullify so this continues endlessly
mState = 0;
mCurButton = null;
break;
}
mHandler.postDelayed(this, 4000);
}
}
}