You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android TextView旋转90°后文本适配空间问题求助

解决TextView旋转后文本适配方向错误的问题

方案一:使用原生垂直文本属性(API 26+)

直接利用Android原生支持的垂直排版属性,无需旋转视图,系统会自动以垂直空间为基准适配文本:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:text="需要垂直显示的文本"
    android:verticalText="true"
    android:textOrientation="upright" />

该方案最简洁,系统会直接按照垂直方向的空间计算文本布局,不会出现旋转后宽度限制导致的文本拆分问题。

方案二:自定义TextView重写测量逻辑(兼容低版本)

若需兼容API 26以下版本,重写onMeasure方法交换宽高的测量逻辑,让系统以原高度作为文本的宽度适配基准:

public class VerticalTextView extends androidx.appcompat.widget.AppCompatTextView {
    public VerticalTextView(Context context) {
        super(context);
    }

    public VerticalTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VerticalTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 交换宽高测量参数,让系统用高度空间计算文本宽度
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        // 交换最终测量的宽高结果
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 旋转画布实现文本垂直显示
        canvas.rotate(-90, getWidth() / 2f, getHeight() / 2f);
        super.onDraw(canvas);
    }
}

布局中使用该自定义View:

<com.yourpackage.VerticalTextView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:text="需要垂直显示的文本" />

方案三:用自定义旋转布局包裹TextView

若不想修改TextView,可编写一个简单的旋转容器,在容器层处理宽高交换和旋转:

public class RotationLayout extends FrameLayout {
    public RotationLayout(Context context) {
        super(context);
    }

    public RotationLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 交换宽高测量参数,让子View以容器高度为宽度基准
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        canvas.save();
        // 旋转画布让子View垂直显示
        canvas.rotate(-90, getWidth() / 2f, getHeight() / 2f);
        super.dispatchDraw(canvas);
        canvas.restore();
    }
}

布局使用示例:

<com.yourpackage.RotationLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="需要垂直显示的文本" />
</com.yourpackage.RotationLayout>

内容的提问来源于stack exchange,提问作者Learning from masters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:45:32