setMeasuredDimension之后的setGravity不起作用

时间:2016-08-01 13:54:49

标签: android textview gravity onmeasure

我创建了课程customTextView extent TextView 我将textAlignment设置为中心。 在onMeasure我更改了textview宽度。

在该textview之后将对齐更改为left 我使用了this.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); 但它没有变成中心

2 个答案:

答案 0 :(得分:0)

在您的课程中添加以下代码。

Runnable runnable = new Runnable() {
            public void run() {
              view.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
            }
   };

Handler handler = new Handler();
handler.postDelayed(runnable,1000);

答案 1 :(得分:0)

像这样?

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        ImageView imageView = (ImageView)((Activity) context).findViewById(R.id.list_r);
        int imageViewHeight = imageView.getMeasuredWidth();

        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int parentHeight = MeasureSpec.getSize(heightMeasureSpec);

        int final_width = parentWidth - 2*imageViewHeight;
        this.setMeasuredDimension(final_width, parentHeight);

        Runnable runnable = new Runnable() {
            public void run() {
                view.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
            }
        };

        Handler handler = new Handler();
        handler.postDelayed(runnable,1000);
    }