gpt4 book ai didi

Android textview 的view bounds 比content 大很多,如何去掉?

转载 作者:行者123 更新时间:2023-11-30 02:19:55 25 4
gpt4 key购买 nike

我的问题是,当我在开发者选项中打开一个设置来查看 View 边界时,我可以看到橙色的“20”文本包含了比所需空间大得多的空间。 (顶部和底部)

我尝试设置:android:includeFontPadding="false" 但它只是简单地向上推内容,在文本容器底部留下一大片空白空间。

如何删除多余的空间?

enter image description here

XML:

 <LinearLayout
android:id="@+id/topDash"
android:layout_width="180dp"
android:layout_height="180dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="@drawable/circle_gray"
android:orientation="vertical" >

<TextView
android:id="@+id/RobotoTextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/sog_C"
android:textColor="@color/blue_medium"
android:textSize="20sp" />

<TextView
android:id="@+id/RobotoTextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="20"
android:textColor="@color/orange"
android:textSize="100sp" />

<TextView
android:id="@+id/robotoTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="KM/H"
android:textColor="@color/gray_darker"
android:textSize="24sp" />
</LinearLayout>

最佳答案

非常好的问题。我不确定是否可以仅在 XML 中执行此操作并且不为 scrollY 属性设置任何硬编码值,但我实现了一个没有硬编码值的小型自定义类,您可以在其他地方使用它而无需任何修改。在这种情况下,onMeasure 方法总能派上用场:) 我在这里使用默认字体。如果您使用不同的字体,请调用 textPaint.setTypeface() 并在 textPaint.getTextBounds 语句之前设置它。

public class CustomTextView extends TextView {
private int newWidth;
private int newHeight;

public CustomTextView(Context context) {
super(context);
}

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

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

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if(newHeight == 0) {
Rect textBounds = new Rect();
Paint textPaint = new Paint();
textPaint.setTextSize(getTextSize());
textPaint.getTextBounds(getText().toString(), 0, getText().length(), textBounds);
int descent = (int) textPaint.descent();
newWidth = textBounds.width();
newHeight = textBounds.height() - 2 * descent;
setScrollY(descent);
}

setMeasuredDimension(newWidth, newHeight);
}
}

但是这个解决方案只适用于数字,为什么只适用于数字,因为下降,这就是为什么我们不能只在 XML 中删除那个额外的空间,它是一个字体属性

descent

关于Android textview 的view bounds 比content 大很多,如何去掉?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28745257/

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