我正在尝试将文本放在TextView子类中的画布中心。它在Eclipse中看起来很好,但不在设备中:
蚀:
设备:
我有理由以这种方式将文本居中。我不在这里解释(也不在代码中),因为它不属于问题。
我已经在使用dips和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:
<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>
也许原因在于TextView.onDraw()中的某个地方,但这超过200行代码,我现在没有时间......甚至不确定它是否存在。
提前致谢!
答案 0 :(得分:0)
尝试使用android:gravity =“center”
<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"
/>