![](/img/trans.png)
[英]In Android how to get the width of the Textview which is set to Wrap_Content
[英]How to `wrap_content` while autosizing an Android TextView?
考慮以下布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:autoSizeTextType="uniform"
android:gravity="center"
android:maxLines="1"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_max="50dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
由於height_max
約束,這導致TextView的文本填充垂直空間,但TextView內部有很多水平填充:
我想要的是設置該TextView的寬度,使其與自動調整大小的文本內容的寬度匹配。 但是,當我設置android:layout_width="wrap_content"
,將根據非自動大小的文本內容設置寬度:
有什么辦法可以同時兼顧兩者-設置文本是否根據已知高度自動調整大小,然后根據自動調整大小的文本寬度設置寬度?
Google的開發人員文檔特別建議不要將wrap_content
與自動大小的TextView一起使用:
注意:如果在XML文件中設置自動調整大小,則不建議對TextView的layout_width或layout_height屬性使用值“ wrap_content”。 可能會產生意想不到的結果。
如果只希望文本的高度為50dp而不是50sp,則可以將textSize設置為50dp。 但是我懷疑您的目標是擁有一個textView,它可以根據布局約束自動縮小文本的大小,而該解決方案將無法完成任務。
如果您確實不能通過使用match_parent
或0dp
的寬度在TextView上留出多余的水平空間,則可以嘗試在創建布局后基於通過使用TextPaint
測量文本來以編程方式設置textview寬度布局參數:
textView.post(new Runnable() {
@Override
public void run() {
TextPaint textPaint = new TextPaint();
textPaint.setTextSize(textView.getTextSize());
float width = textPaint.measureText(textView.getText().toString());
ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
layoutParams.width = (int)width;
textView.setLayoutParams(layoutParams);
}
});
請記住,如果您選擇這條路線,則可能需要向其中添加一些左右填充。 即使將TextView的填充設置為零,TextView也具有某種內部填充-但是當直接設置width參數時,它將被覆蓋。
嘗試將0dp
(等於MATCH_CONSTRAINT
)用於TextView
的android:layout_width
屬性。
你可以試試這個
<TextView
android:id="@+id/vName"
android:layout_width="56dp"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Groupa"
app:autoSizeMinTextSize="12sp"
app:autoSizeMaxTextSize="20sp"
app:autoSizeTextType="uniform"
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.