我需要在布局中包含 3 个文本。中间的 textView
是红色的,另外两个是黑色的。所以我将它添加到 relativelayout
并将 layout
设置为 textView2 到 textView1 的右侧,textView3 到 textView2 的右侧
但是当第三个 TextView 中的文本更大时,它应该来自 textview one。我明白了。
现在我应该怎么做才能得到这样的东西?
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/rel_lay"
android:background="#DFDFDF"
android:padding="2dip" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dip"
android:text="TextView"
android:textColor="#000000" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/textView1"
android:text="TextView"
android:textColor="#FF0000" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="false"
android:layout_toRightOf="@+id/textView2"
android:text="TextView when the third text is longer"
android:textColor="#000000" />
</RelativeLayout>
这是有 3 个 textView 的相对布局。
最佳答案
只需使用一个 TextView
并根据需要设置文本。您知道要为红色 设置哪个文本。所以您需要的是开始文本的索引 和结束文本。
使用下面的代码。
SpannableString spanText = new SpannableString("My Name is Chintan Rathod");
spanText.setSpan(new ForegroundColorSpan(Color.parseColor("#FF0000")), 5 /*start index*/, 10 /*end index*/, 0);
textView.setText(spanText);
这里,我传了5和10,但是你可以传自己的索引。但要确保 index 在不会触发 IndexOutOfBoundException
的范围内关于android 在布局中排列 TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15217628/