在过去的两个小时中,我一直在为此苦苦挣扎,而我只是无法获得答案。我想要我的相对布局的中心,因为我想使用画布在那里画一个圆。我已经尝试过的


ViewTreeObserver.OnGlobalLayoutListener
OnStart()


这是我的代码:

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

    Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.WHITE);
    Bitmap bg = Bitmap.createBitmap(480, 500, Bitmap.Config.ARGB_8888);
    canvas = new Canvas(bg);
    rel = (RelativeLayout) findViewById(R.id.relPaint);
    //canvas.drawPaint(paint);
    paint.setColor(Color.parseColor("#CD5C5C"));
    canvas.drawCircle(centreX, centreY, 50, paint);
    int sdk = android.os.Build.VERSION.SDK_INT;
    if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        rel.setBackgroundDrawable(new BitmapDrawable(getResources(), bg));
    } else {
        rel.setBackground(new BitmapDrawable(getResources(), bg));
    }
}

@Override
protected void onStart() {
    centreX = rel.getX() + rel.getWidth()  / 2;
    centreY = rel.getY() + rel.getHeight() / 2;
    super.onStart();
}


变量rel,centerX和centerY全局声明。谢谢。

最佳答案

看看Activity LifecycleonCreate()onStart()之前被调用。首先要绘制圆,然后再计算布局的中心。在OnCreate()中执行所有操作。

然后像这样计算centreXcentreY

rel.post(new Runnable() {
@Override
  public void run() {
    centreX = rel.getWidth() / 2;
    centreY = rel.getHeight() / 2;

    Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(Color.WHITE);
    Bitmap bg = Bitmap.createBitmap(480, 500, Bitmap.Config.ARGB_8888);
    canvas = new Canvas(bg);
    rel = (RelativeLayout) findViewById(R.id.relPaint);
    //canvas.drawPaint(paint);
    paint.setColor(Color.parseColor("#CD5C5C"));
    canvas.drawCircle(centreX, centreY, 50, paint);
    int sdk = android.os.Build.VERSION.SDK_INT;
    if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
      rel.setBackgroundDrawable(new BitmapDrawable(getResources(), bg));
    } else {
      rel.setBackground(new BitmapDrawable(getResources(), bg));
    }
  }
});

10-08 15:29