【问题标题】:android arranging text view in a layoutandroid在布局中安排文本视图
【发布时间】:2013-03-05 06:57:05
【问题描述】:

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

但是当第三个文本视图中的文本更大时,它应该是文本视图之一。我明白了。

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

  <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的相对布局。

【问题讨论】:

  • 你想为你的第二个文本视图赋予 红色 颜色吗?和其他两个黑色?如果是的话,我有一个文本视图的解决方案,你可以做到这一点。
  • @ChintanRathod 我该怎么做?文本从 java 类传递。

标签: android android-layout


【解决方案1】:

只需使用一个TextView 并根据需要设置文本。您知道要为 Red 颜色设置哪些文本。所以你需要的是起始文本索引结束文本

使用以下代码。

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

的范围内

【讨论】:

    【解决方案2】:

    使用Spanned 类和一个TextView 可能会更好。您尝试实现它的方式是,TextView #3 必须在宽度上填充_parent 并且能够知道 TextView #2 的结束位置。

    【讨论】:

      猜你喜欢
      • 2011-12-03
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多