如何使用Java代码在TextView中垂直居中文本?

时间:2017-10-23 07:59:28

标签: java android textview alignment

我知道这个问题已经多次被问过了。我已经阅读了大部分内容,但它们对我不起作用,所以不要打扰重复标记。

这是我的代码,以及到目前为止我尝试过的内容:

RelativeLayout container = new RelativeLayout(this.getContext());

TextView tv = new TextView(this.getContext());
tv.setText(txt); // a single digit like '3'
tv.setLines(1);
tv.layout(0, offsety, cellszie, offsety+cellsize);

tv.setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER);
tv.setGravity(Gravity.CENTER);

// I also tried CENTER_VERTIAL and the following line
// tv.setGravity(CENTER_VERTIAL| CENTER_HORIZONTAL);

// I also tried giving LayoutParams to tv like this:
// tv.setLayoutParams(new LayoutParams(cellsize, cellsize));
// tv.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
// tv.setLayoutParams(new LayoutParams(MATCH_PARENT, MATCH_PARENT));

container.addView(tv);

字符水平居中,但它垂直浮动在TextView的顶部。设置gravityLayoutParams不会改变其行为。

如何使其垂直居中?

3 个答案:

答案 0 :(得分:1)

将此类用于VerticalTextView。

public class VerticalTextView extends TextView {
final boolean topDown;

public VerticalTextView(Context context, AttributeSet attrs){
    super(context, attrs);
    final int gravity = getGravity();
    if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
        setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
        topDown = false;
    }else
        topDown = true;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
    super.onMeasure(heightMeasureSpec, widthMeasureSpec);
    setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}

@Override
protected void onDraw(Canvas canvas){
    TextPaint textPaint = getPaint();
    textPaint.setColor(getCurrentTextColor());
    textPaint.drawableState = getDrawableState();

    canvas.save();

    if(topDown){
        canvas.translate(getWidth(), 0);
        canvas.rotate(90);
    }else {
        canvas.translate(0, getHeight());
        canvas.rotate(-90);
    }
    canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());

    getLayout().draw(canvas);
    canvas.restore();
}
}

答案 1 :(得分:1)

你可以这样做

RelativeLayout container = new RelativeLayout(this.getContext());
View view = layoutInflater.inflate(R.layout.my_layout_file, null);
container.addView(view);

其中R.layout.my_layout_file包含带有重心的文本视图。在这里你可以像这样获得textview的对象

textviewObject = (TextView)view.findViewById(R.id.textViewId) 

答案 2 :(得分:1)

尝试将 RelativeLayout.LayoutParams 设置为RelativeLayout

RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
container.setLayoutParams(relativeLayoutParams)

然后设置TextView的重力:

tv.setGravity(Gravity.CENTER);

然后将视图添加到RelativeLayout:

container.addView(tv);