设置屏幕属性视图

Set a view on screen-properities

在下面的代码中,按钮会在点击时改变它的位置。但有时,按钮会移出屏幕,导致无法再点击。如何解决?

@Override

public void onClick(View v) {

view.getParent();
    Random r = new Random();
    View decorView = getWindow().getDecorView();
    int screenWidth = decorView.getWidth();
    int screenHeight = decorView.getHeight();
      long startTime =  SystemClock.elapsedRealtime();
      i++;


    if (i == 1 ) {

        start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
        start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
    }
    if (i == 2 ) {
        start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
        start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
    }

    else if (i == 3) {
        long difference = SystemClock.elapsedRealtime()  - startTime;

          Intent intent = new Intent(Game.this, MainScreen.class);
          intent.putExtra("time",difference);

          textview1.setText(getIntent().getStringExtra("time"));
        finish();
    }


}

您遇到的问题似乎是您可能在 RelativeLayout 中将 wrap_content 用作 width/height,但您获取了屏幕的宽度和高度,而不是包含按钮的布局.

您应该使用 getParent() 方法来获取 RelativeLayout 宽度和高度。

RelativeLayout myRelativeLayout = (RelativeLayout) myButton.getParent();
int screenWidth = myRelativeLayout.getWidth();
int screenHeight = myRelativeLayout.getHeight();