0

我正在做一个简单的应用程序,当用户单击按钮时。背景颜色将使用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;
}
4

1 回答 1

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);
            }
        }
    }
于 2013-01-21T10:49:52.407 回答