这是我自定义的Textview
public class RectTextView extends android.support.v7.widget.AppCompatTextView {
public RectTextView(Context context) {
super(context);
}
public RectTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public RectTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
center();
}
private void center() {
int max = Math.max(getMeasuredHeight(), getMeasuredWidth());
setMeasuredDimension(max, max);
}
}
然后放到xml中设置gravity=center,长宽包裹内容,发现这样保障了长=宽,textview的内容却没有居中,求大神支招
帮你试了一下,在布局文件中的RectTextView加上 android:gravity="center" 就行
布局中加 android:gravity="center"或者在RectTextView类里面添加
private void center() {
int max = Math.max(getMeasuredHeight(), getMeasuredWidth());
setGravity(Gravity.CENTER);
setMeasuredDimension(max, max);
}
既然是自定义你就在ondraw中自己判断是否居中然后计算text的位置
1.定义画笔
paint = new Paint();
paint.setColor(Color.GRAY);
paint.setTextSize(textSize);
2.获取高度
private int getTextHeight(){
Rect rect = new Rect();
paint.getTextBounds("F", 0, "F".length(), rect);
return rect.height();
}
这个方法获取高度height,同理可得宽度width
3.onDraw时:
geLayoutParams().width = width +padding * 2;
getLayoutParams().height = height+padding * 2;
canvas.drawText(“F",padding,padding, paint);