android 在布局中排列 TextView

标签 android android-layout

我需要在布局中包含 3 个文本。中间的 textView 是红色的,另外两个是黑色的。所以我将它添加到 relativelayout 并将 layout 设置为 textView2 到 textView1 的右侧,textView3 到 textView2 的右侧

this is what i have done

但是当第三个 TextView 中的文本更大时,它应该来自 textview one。我明白了。

when the 3rd text is longer i get this

现在我应该怎么做才能得到这样的东西?

this is what i need

  <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);

这里,我传了510,但是你可以传自己的索引。但要确保 index 在不会触发 IndexOutOfBoundException

的范围内

关于android 在布局中排列 TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15217628/

相关文章:

android - 如何修复Android Studio 1.4上的错误 “Failed to resolve:…”

android - 指定的子项已有父项。填充表格行时,您必须对 child 的 parent 调用 removeChild()

android - 如何在android中修改来电和去电屏幕 View

Android:强制显示 fragment 的滚动条

java - 旋转单元格停止媒体播放器android

java - Android:键盘未显示在焦点上

android - 应用程序可以包含用户可以控制应用程序权限的页面吗?

android - 访问 main.xml 中的变量

android - ListView 中的动态列数

android - 带有 collapsingToolbarLayout、RelativeLayout 和 NestedScrollView 的自定义底部 float 按钮