Android在布局中排列文本视图

4
我需要在布局中有三个文本。中间的textView是红色的,另外两个是黑色的。所以我将它添加到一个relativelayout中,并将layout设置为textView2放置在textView1的右侧,textView3放置在textView2的右侧。
但是当第三个文本视图中的文本更长时,它应该出现在textView1中。但我得到了这个结果。
现在我该怎么做才能得到像这样的东西?
  <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的相对布局。


您想将第二个文本视图设置为红色,其他两个设置为黑色吗? 如果是的话,我有一个解决方案可以通过一个文本视图来实现。 - Chintan Rathod
@ChintanRathod 我该怎么做?文本是从Java类传递的。 - null pointer
2个回答

1
你可以尝试使用Spanned类和一个TextView,这样可能会更好。如果按照你当前的实现方式,TextView #3需要用fill_parent填充宽度,并且需要知道TextView #2的结束位置。

1

只需使用一个 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);

在这里,我已经传递了510,但你可以传递自己的索引。但要确保索引在范围内,否则将触发IndexOutOfBoundException

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接