如何使用Random()自动循环颜色,只需单击一个按钮即可

时间:2013-01-21 10:40:11

标签: android android-layout

我正在做一个简单的应用程序,当用户点击按钮时。使用Random(),背景颜色将不断变换为不同的颜色。我该如何实现呢?这是我的代码

if (looper == false) 
{
    Jbutton1.setText("loop now ");
    int color;
    Random rnd = new Random();
    color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),                             rnd.nextInt(256));
    JmyScreen.setBackgroundColor(color);
    looper = true;
}
else
{
    Toast.makeText(getApplicationContext(), "stop loop",Toast.LENGTH_SHORT).show();
    Jbutton1.setText("stop looping");
    JmyScreen.setBackgroundColor(Color.WHITE);
    looper = false;
}

1 个答案:

答案 0 :(得分:0)

此处按钮的背景每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);
            }
        }
    }