【发布时间】:2012-04-25 09:39:16
【问题描述】:
我有一个布局,其中两个 TextView 将显示在同一行,这样
如果 TextView1 是短文本,TextView2 应该紧挨着 TextView1(IMAGE1),如果 TextView1 是长文本,TextView2 应该在同一行的 Layout 的右上角(IMAGE2)
我怎样才能做到这一点?
【问题讨论】:
我有一个布局,其中两个 TextView 将显示在同一行,这样
如果 TextView1 是短文本,TextView2 应该紧挨着 TextView1(IMAGE1),如果 TextView1 是长文本,TextView2 应该在同一行的 Layout 的右上角(IMAGE2)
我怎样才能做到这一点?
【问题讨论】:
我使用带有 android:layout_weight 属性的简单水平线性布局,它就像你想要的那样工作。 示例:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/text1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="teeeeeeeext1"/>
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text2"/>
</LinearLayout>
【讨论】:
使用这样的布局..
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="38dp"
android:layout_toRightOf="@+id/editText1" />
</RelativeLayout>
edittext 1 将 edittext2 推到它的右边...取决于其中的文本..
【讨论】:
您可以为第一个文本视图设置android:maxWidth 属性。所以你的布局应该是这样的:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="200dp"
android:text="sdfksdofsdfsdfsdfsadfgwagrswargweqrgeqrgqwergeqrgeqrg"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/textView1"
android:text="text2"
/>
【讨论】:
编辑:
我显然误读(或未完全阅读)您的问题。只是不要介意我的回答 - 我投票给 mxy's :)
上次我遇到同样的问题时,我无法找到或破解一个简单的解决方案。计算像素不是一种选择(至少对我来说不是)。但我找到了一个最终导致相同显示概念的解决方法,那就是使用SpannableStringBuilder。
我假设您想要两个不同的 TextView,因为您希望它们具有不同的颜色(或大小、样式或字体)。
我们的想法是对整个事情使用单个 TextView,并在对您的视图执行 setText 之前准备一个 SpannableString。
通过使用 ForegroundColorSpan、TextAppearanceSpan 等的组合,您可以使您的单个 TextView 看起来像具有不同样式的不同 TextView,并排放置,并根据需要换行到下一行。
链接:
【讨论】: