我有一个文本视图,它可以取值 "全部选择 "或 "全部取消选择"。我想将宽度设置为这两个字符串中最长的一个的长度。因为这可以随着语言的变化而变化)。我如何设置这个?
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
app:layout_constraintHeight_min="32dp">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/name_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:textColor="@color/blackColor"
android:textSize="16sp"
android:textStyle="normal"
android:inputType="textFilter|textMultiLine"
app:fontFamily="@font/lato_semibold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/select_text"
app:layout_constraintHorizontal_bias="0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Google Nest" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/select_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingEnd="16dp"
android:textSize="12sp"
android:text="@string/selectAll"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1"
app:layout_constraintTop_toTopOf="parent"
tools:text="Select All" />
你可以使用TextView的Paint对象来测量每个文本的宽度,然后像这样手动应用宽度。
TextView textView = findViewById(R.id.my_text_view);
String selectText = getString(R.string.select_all);
String deselectText = getString(R.string.deselect_all);
float selectWidth = textView.getPaint().measureText(selectText);
float deselectWidth = textView.getPaint().measureText(deselectText);
ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
layoutParams.width = (int) Math.max(selectWidth, deselectWidth);
textView.setLayoutParams(layoutParams);
请注意,以这种方式测量宽度不会考虑到包裹文本。所以,如果有些译文很长的话,这种方法可能就不适用了。