HengFeng

--博观而约取,厚积而薄发
  博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

【原创】SimpleAdatper动态改变Layout布局

Posted on 2013-02-06 17:24  hengfeng  阅读(383)  评论(0编辑  收藏  举报

大部分有聊天功能的APP的聊天界面都是使用上图所示的界面布局,即本方和对方的聊天内容分别放置在屏幕的左右两边。

要实现上述的效果,可以使用ListView绑定一个SimpleAdatper子类,在SimpleAdatper子类中重写getView方法。在getView中判断消息是谁发送的,并返回相应的View:

    //定义一个扩展的SimpleAdapter
    private class ExSimpleAdapter extends SimpleAdapter{
        
        public ExSimpleAdapter(Context context,
                List<? extends Map<String, ?>> data, int resource,
                String[] from, int[] to) {
            super(context, data, resource, from, to);
            // TODO Auto-generated constructor stub
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            LayoutInflater mLayoutInflater = LayoutInflater.from(ChatActivity.this);
            if(mMsgFromList.get(position))
                convertView = mLayoutInflater.inflate(R.layout.message_right, null);
            else
                convertView = mLayoutInflater.inflate(R.layout.message_left, null);
            
            return super.getView(position, convertView, parent);
        }
    }

1. 这里message_right和message_left就是左右布局的Layout.

2. private ArrayList<Boolean> mMsgFromList = new ArrayList<Boolean>(); 用于记录每条消息是谁发送的。

这样每次调用mSimpleAdapter的notifyDataSetChanged()方法就会更新相应的聊天界面了。