gpt4 book ai didi

android - 防止多行 TextView 不必要地扩展到它的最大宽度

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:07:15 27 4
gpt4 key购买 nike

扩展为多行的 TextView 似乎会自动扩展以适应它的最大可能宽度。我怎样才能防止这种情况发生?

这是一个示例布局 (test.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<TextView
android:background="@color/green"
android:layout_alignParentRight="true"
android:id="@+id/foo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="This is the message a much shorter message"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@color/black" />
</RelativeLayout>

TextView shown with maximum width

如果我在左侧添加边距,它会正确地缩小 TextView 的宽度(无需重新格式化内容),但边距的大小必须根据 TextView 的内容进行计算。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<TextView
android:layout_marginLeft="32dp"
android:background="@color/green"
android:layout_alignParentRight="true"
android:id="@+id/foo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="This is the message a much shorter message"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@color/black" />
</RelativeLayout>

TextView show with margin

最佳答案

您可以在计算宽度的地方使用自定义 TextView 和覆盖方法 onMeasure():

public class WrapWidthTextView extends TextView {

// ...

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);

Layout layout = getLayout();
if (layout != null) {
int width = (int)FloatMath.ceil(getMaxLineWidth(layout))
+ getCompoundPaddingLeft() + getCompoundPaddingRight();
int height = getMeasuredHeight();
setMeasuredDimension(width, height);
}
}

private float getMaxLineWidth(Layout layout) {
float max_width = 0.0f;
int lines = layout.getLineCount();
for (int i = 0; i < lines; i++) {
if (layout.getLineWidth(i) > max_width) {
max_width = layout.getLineWidth(i);
}
}
return max_width;
}
}

关于android - 防止多行 TextView 不必要地扩展到它的最大宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9749200/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com