单击图像视图的周边内部,随机移动按钮

时间:2014-07-14 05:40:39

标签: android onclick imageview imagebutton

基本上这就是我想要做的。我想要一个ImageButton,一旦点击就会随机改变位置,但是按钮必须保持在我在屏幕上的ImageView中。到目前为止,我的按钮随机移动但不确定如何将其移动限制在ImageView的边界内。请尽可能帮助,我还附上了我当前的Java代码。

JAVA CODE:

public class MainActivity extends Activity {

private ImageButton startbutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    final ImageView buttonfield = (ImageView) findViewById(R.id.imageView1);
    startbutton = (ImageButton) findViewById(R.id.btn);
    startbutton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {


        Random r = new Random();
        int buttonHeight;
        int buttonWidth;
        buttonHeight = startbutton.getHeight();
        buttonWidth = startbutton.getWidth();
        int xLeft = r.nextInt(480 + buttonHeight);
        int yUp = r.nextInt(900 + buttonWidth);
        int xRight = r.nextInt(480 + buttonHeight);
        int yDown = r.nextInt(900 + buttonWidth);

        startbutton.setX(xLeft);       
        startbutton.setY(yUp);
        startbutton.setX(xRight);
        startbutton.setY(yDown);
        }





    });
    }
}

0 个答案:

没有答案