如何在不挤压的情况下将视图与另一个视图对齐

时间:2016-11-02 20:44:46

标签: android xml android-layout

< p>当然这是一个经常使用的例子,但我似乎无法使用LinearLayout(或RelativeLayout)来解决它,但也许我错过了一些东西。< / p> < p>最好用图片说明:< / p> < p>< a href =“https://i.stack.imgur.com/oDx2g.png”rel =“nofollow noreferrer”>< img src =“https://i.stack.imgur。 com / oDx2g.png“alt =”在此处输入图像说明“>< / a>< / p> < p>我有一个基本的textview chatbubble与右边对齐的另一个textview(消息的时间戳)。< / p> < p>两者都是< code> wrap_content< / code> (但时间戳可以设置为恰好40dp,但似乎并不重要。)< / p> < p>现在在第一个(顶部)消息中,它很短,因此您可以看到右侧的视图。< / p> < p>但是在第二个字符串很长,所以< code> wrap_content< / code>占据了手机的整个宽度,将时间戳文本视图推出屏幕(水平线性布局,但是相对的< code> toRightOf< / code>也是如此)< / p> < p>那么如何将时间戳与另一个视图对齐,但时间戳将是保证大小(不包裹/压缩 - 消息气泡串换行)< / p> < p>(我意识到我< em>可以< / em>使用RTL布局,但我有来自双方的消息所以我在其他情况下需要LTR + min sdk api 17对于布局黑客来说太高了) < / p为H. < p>任何帮助都会非常感激,因为我一定错过了一些明显的东西。< / p>

2 个答案:

答案 0 :(得分:1)

如果您使用水平LinearLayout的{​​{1}}窗口小部件,并且其中一个子窗口想要占用所有可用的水平空间,那么您应该使用布局权重。

对于第一个orientation集:

TextView

对于第二个layout_width="0dp" layout_weight="1"

TextView

在这种情况下,您说第二个layout_width="wrap_content" 将占用所需的水平空间,第一个TextView将采用其余的。 " 0dp"只是一个优化,以防止额外的布局测量调用。

答案 1 :(得分:1)

这样做:

<LinearLayout
   android:width="match_parent"
   android:height="wrap_content"
   android:orientation="horizontal">

   <!-- the text -->
   <TextView
           android:width="0dp"
           android:height="wrap_content"
           android:weight="1"/>
<!-- the time -->
   <TextView
           android:width="match_parent"
           android:height="wrap_content"/>
</LinearLayout>

或者这个:

 <LinearLayout
       android:width="match_parent"
       android:height="wrap_content"
       android:orientation="horizontal">

       <!-- the text -->
       <TextView
               android:width="match_parent"
               android:height="wrap_content"
               android:maxWidth="300dp"/> <!-- can be a different dimention -->
    <!-- the time -->
       <TextView
               android:width="match_parent"
               android:height="wrap_content"/>
    </LinearLayout>