无法弄清楚如何获得relativelayout的中心

时间:2015-02-23 09:05:59

标签: java android relativelayout

过去2个小时我一直在努力解决这个问题,而我却无法得到答案。我想要我的relativelayout的中心,因为我想用画布在那里画一个圆圈。我已经尝试过了:

  • 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,centreX和centreY在全球范围内声明。感谢。

1 个答案:

答案 0 :(得分:1)

看看Activity Lifecycle。在onCreate()之前调用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));
    }
  }
});