【问题标题】:Android bubble chat different layout after first user message第一次用户消息后Android气泡聊天不同的布局
【发布时间】:2015-10-30 08:43:27
【问题描述】:

我正在我的聊天应用程序的列表视图适配器中创建“气泡”样式的消息表示。这是我想要达到的效果:

如您所见,如果用户连续写了两条或多条消息,则第二条用户消息应该以不同的布局显示(没有图片)。我怎样才能做到这一点?因为看起来很复杂。我应该检查适配器中的最后一个消息类型(看起来不是那么可靠的解决方案)吗?或者在我的消息对象中添加并稍后检查其他字段?任何示例或帮助将不胜感激。

【问题讨论】:

  • 使用不同的 9 个补丁。还有一个布尔值(比如isFirst)。
  • 是的,将来我肯定会使用九个补丁。我知道该解决方案可能基于简单的布尔值/布尔值。只是我从架构的角度感兴趣 - 在代码中使用布尔值的确切位置。看到任何代码示例都会很棒。
  • To see any code example would be great. 对我们来说也是如此。为了能够帮助您。
  • 不管怎样,根据疯狂的猜测:你展示图片的地方是将布尔值设置为 true 的好地方。在显示第一个 TextView 之后(您可能更喜欢设置整数计数器,而不是布尔值),将其设置为 false。

标签: java android android-layout android-listview chat


【解决方案1】:

我假设你有一个像这样的 Message 类:

class Message {
    public String text;
    public String avatar;
}

因此,在 getView 方法中,您可以轻松检查上一项:

ArrayList<Message> mMessages;
...
public View getView (int position, View convertView, ViewGroup parent){      
    if( convertView == null ){
         if (position > 0 && mMessages.get(position-1).avatar.equal(mMessages.get(position).avatar)){
              // set layout for second message style
              convertView = inflater.inflate(R.layout.list_without_avatar, parent, false);
         } else {
              // set layout for the first message style
              convertView = inflater.inflate(R.layout.list_with_avatar, parent, false);
         }             
    }
    ...
    return convertView;
}

希望对您有所帮助!

【讨论】:

  • 是的,你说得对,但还有另一种类似于你的方法。检查用户 ID 与上一个项目,如果相同则隐藏图片,如果不显示图片 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 2022-11-18
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多