Android 无法在画布中居中显示文本

Android 无法在画布中居中显示文本,android,android-layout,Android,Android Layout,我正在尝试在TextView子类的画布中居中文本。它在Eclipse中看起来不错,但在设备中却不行: 月食: 设备: 我想用这种方式将文本居中是有原因的。我在这里没有解释(代码中也没有),因为它不属于问题 我已经在使用DIP和sps了 守则: package com.example.test2; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; imp

我正在尝试在TextView子类的画布中居中文本。它在Eclipse中看起来不错,但在设备中却不行:

月食:

设备:

我想用这种方式将文本居中是有原因的。我在这里没有解释(代码中也没有),因为它不属于问题

我已经在使用DIP和sps了

守则:

package com.example.test2;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;

public class CenterTest extends TextView {
    private Paint paint;
    private Paint paint2;
    private Rect bounds;

    public CenterTest(Context context) {
        super(context);
    }

    public CenterTest(Context context, AttributeSet attrs) {
        super(context, attrs);

        paint = new Paint();
        paint2 = new Paint();
        bounds = new Rect();
    }

    public void draw(Canvas canvas) {
        canvas.save();

        int width = getWidth();
        int height = getHeight();

        //draw background
        paint2.setColor(Color.rgb(0, 0, 0));
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(0, 0, width, height, paint2);

        //measure text
        paint.setTextSize(getTextSize());
        paint.getTextBounds(getText().toString(), 0, getText().toString().length(), bounds);
        int textWidth =  bounds.width();
        int textHeight =  bounds.height();

        //center before drawing text
        canvas.translate((width / 2) - (textWidth / 2), 0);
        canvas.translate(0, (height / 2) - (textHeight / 2));

        //let TextView.onDraw() do the rest
        super.onDraw(canvas);

        canvas.restore();
    }
}
XML:


可能原因在TextView.onDraw()中的某个地方,但那有200多行代码,我现在没有时间。。。甚至不知道它是否在那里


提前谢谢

尝试使用android:gravity=“center”


不,我说我想换个方向居中。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff" 
    >
    <com.example.test2.CenterTest
        android:layout_width="100dip"
        android:layout_height="30dip"
        android:text="label"
        android:textColor="#ffffff"
        android:singleLine="true"
        android:textSize="12sp"
    />
</RelativeLayout>
<com.example.test2.CenterTest
    android:layout_width="100dip"
    android:layout_height="30dip"
    android:text="label"
    android:textColor="#ffffff"
    android:singleLine="true"
    android:textSize="12sp"
    android:gravity="center"
/>