美文网首页
Android实现简易的聊天气泡内容可变长适配布局

Android实现简易的聊天气泡内容可变长适配布局

作者: Jk_zhuang | 来源:发表于2019-01-10 18:17 被阅读0次

布局横向排列,有3个元素,分别为a,b,c,先上效果图:
1)当b比较小时的效果:


effect_1.png

2)当b比较大时的效果:


effect_2.png

  下面说下实现的效果,a为头像,固定宽度,b为聊天内容,可变长,需根据内容长短来适配,c为聊天时间,内容长度有限。a固定在左边,b固定在a的右边,c固定在b的右边。b的宽度可变,变的时候c随着b右移,边界是c到达屏幕最右端,此时b的宽度应达到最大。
  刚开始用ConstraintLayout、RelativeLayout等布局常规的写法都好像实现不了这种效果,最后折中的方案往往就是把b的宽度给固定住,当然还得适配下不同分辨率,再或者可以自定义View去实现。后来突发奇想,通过下面的布局可以直接解决,下面直接附上布局文件 :

item_chat.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingTop="10dp"
    android:paddingBottom="10dp">

    <ImageView
        android:id="@+id/tv_title"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:src="@mipmap/ic_launcher"
        tools:text="Title" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:paddingStart="0dp"
        android:paddingLeft="0dp"
        android:paddingEnd="60dp"
        android:paddingRight="60dp"
        android:singleLine="true"
        android:textSize="16sp"
        tools:text="Hello, i am Android." />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="-60dp"
        android:layout_marginLeft="-60dp"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:textSize="10sp"
        tools:text="2019/1/10" />

</LinearLayout>

另:代码中的60可根据实际场景设定,要是c可变宽度的话,在java代码获取下c的宽度,然后再分别设置b的paddingRight和c的layout_marginLeft就行了。

相关文章

网友评论

      本文标题:Android实现简易的聊天气泡内容可变长适配布局

      本文链接:https://www.haomeiwen.com/subject/fhzarqtx.html