您可以以编程方式执行此操作:
xml:
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="28dp"
android:background="#303F9F"
android:text="Short Text"
app:layout_constraintEnd_toStartOf="@+id/guideline2"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="parent"
android:gravity="start" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginTop="24dp"
android:background="#303F9F"
android:text="This is a very long text"
app:layout_constraintEnd_toStartOf="@+id/guideline2"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toBottomOf="@+id/textView"
android:layout_marginRight="8dp"
android:gravity="start" />
<android.support.constraint.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
</android.support.constraint.ConstraintLayout>
背景颜色是看到变化。
在代码中获取较大 TextView 的宽度并将其设置为较小的。
textView1 = findViewById(R.id.textView);
textView2 = findViewById(R.id.textView2);
textView1.measure(0,0);
textView2.measure(0,0);
int len1 = textView1.getMeasuredWidth();
int len2 = textView2.getMeasuredWidth();
if (len1 > len2) {
textView2.getLayoutParams().width = len1;
} else {
textView1.getLayoutParams().width = len2;
}
而且您不必总是使用ConstraintLayout
.