如何随机放置ImageButtons并防止它们重叠?

时间:2014-03-10 17:50:08

标签: java android imagebutton

我想为ImageButton创建数组以防止我的对象重叠,我想在params.height之后添加它。所以我的问题是如何做到这一点?

到目前为止,这是我的代码:

public class Play extends Activity implements OnClickListener {
    final Context context = this;
    MediaPlayer mplayer;
    MediaPlayer mplPlayer1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);
        text = (TextView) this.findViewById(R.id.textView2);
        countDownTimer = new MyCountDownTimer(startTime, interval);
        text.setText(text.getText() + String.valueOf(startTime / 1000));
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.RelativeLayout1);
        rl.setBackgroundResource(R.drawable.background);
        /*
         * for-loop creates my imagebutton and then i place them in random
         * position but the problem is that its overlapping too much So how to
         * prevent it?
         */
        for (int i = 0; i < 10; i++) {
            ImageButton btn = new ImageButton(this);
            btn.setBackgroundResource(R.drawable.apple);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            btn.setLayoutParams(params);
            params.width = 83;
            params.height = 80;
            int left = (int) (Math.random() * 1024 + 83);
            int right = (int) (Math.random() * 600 + 20);
            if (left == 600 & right == 600) {
                params.setMargins(left, 10 + 2, right, 0);
            } else
                params.setMargins(left, 50 - 1, right, 0);
            btn.setLayoutParams(params);
            rl.addView(btn);
            btn.setId(i);
            btn.setOnClickListener(this);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

      int left = (int) (Math.floor((Math.random()*1024)/83.0) * 83 + 83);
      int right = (int) (Math.floor((Math.random()*600)/80.0)*80 + 20);

这会将每个随机数与按钮的宽度和高度分开。