基于RecyclerView实现的实现多样化的item样式——类似IM即时通讯聊天界面的布局效果


首先看一下实现的效果图:


RecyclerView实现多样化的item样式一般的实现代码还是比较简单的,直接上代码:

ChatDetailAdapter适配器:

package com.alter.popupwindowmenu.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alter.popupwindowmenu.Command.C;
import com.alter.popupwindowmenu.R;
import com.alter.popupwindowmenu.model.ChatMessage;
import com.alter.popupwindowmenu.model.UserInfo;

import java.util.List;

/**
 * @CreateDate: 2018/1/26
 * @Author: lzsheng
 * @Description: 适配器,根据不同的数据类型,展示不同的UI效果
 * @Version:
 */
public class ChatDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;
    private List<ChatMessage> mChatMessages;
    private OnRecyclerViewItemLongClick mOnRecyclerViewItemLongClick;

    private final int TYPE_MSG_SEND = C.TYPE_MSG_SEND;              //
    private final int TYPE_MSG_RECEIVE = C.TYPE_MSG_RECEIVE;          //

    public ChatDetailAdapter(Context context) {
        this.mContext = context;
    }

    public void setChatMessages(List<ChatMessage> chatMessages) {
        mChatMessages = chatMessages;
    }

    public void setOnRecyclerViewItemLongClick(OnRecyclerViewItemLongClick onRecyclerViewItemLongClick) {
        mOnRecyclerViewItemLongClick = onRecyclerViewItemLongClick;
    }

    /**
     * @CreateDate: 2018/2/3
     * @Author: lzsheng
     * @Description: 根据数据的类型, 返回不同的ItemViewType
     * @Params: [position]
     * @Return: int
     */
    @Override
    public int getItemViewType(int position) {
        if (mChatMessages != null && mChatMessages.size() > 0) {
            int from = mChatMessages.get(position).getFrom();
            if (from == C.TYPE_MSG_SEND) {
                return TYPE_MSG_SEND;
            } else if (from == C.TYPE_MSG_RECEIVE) {
                return TYPE_MSG_RECEIVE;
            }
        }
        return 0;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_MSG_SEND:
                HolderChatSend holderChatSend = new HolderChatSend(
                        LayoutInflater.from(mContext).inflate(R.layout.rv_item_chat_msg_send, parent, false));
                return holderChatSend;
            case TYPE_MSG_RECEIVE:
                HolderChatReceive holderChatReceive = new HolderChatReceive(
                        LayoutInflater.from(mContext).inflate(R.layout.rv_item_chat_msg_receive, parent, false));
                return holderChatReceive;
            default:
                return null;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (mChatMessages != null) {
            ChatMessage chatMessage = mChatMessages.get(position);
            int from = chatMessage.getFrom();
            switch (from) {
                case TYPE_MSG_SEND:
                    String msgContentSend = chatMessage.getMsgContent();
                    ((HolderChatSend) holder).tvMsgContent.setText(msgContentSend);
                    break;
                case TYPE_MSG_RECEIVE:
                    UserInfo userInfo = chatMessage.getUserInfo();
                    ((HolderChatReceive) holder).tvNickName.setText(userInfo.getNickName());
                    String msgContentReceive = chatMessage.getMsgContent();
                    ((HolderChatReceive) holder).tvMsgContent.setText(msgContentReceive);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public int getItemCount() {
        if (mChatMessages != null && mChatMessages.size() > 0) {
            return mChatMessages.size();
        }
        return 0;
    }

    class HolderChatSend extends RecyclerView.ViewHolder implements View.OnLongClickListener {

        TextView tvNickName;
        TextView tvMsgContent;
        LinearLayout layoutChat;
        MotionEvent event;

        public HolderChatSend(View itemView) {
            super(itemView);
            tvNickName = (TextView) itemView.findViewById(R.id.textview_nick_name);
            tvMsgContent = (TextView) itemView.findViewById(R.id.textview_message);
            layoutChat = (LinearLayout) itemView.findViewById(R.id.layout_message);
            layoutChat.setOnLongClickListener(this);
        }

        @Override
        public boolean onLongClick(View v) {
            if (mOnRecyclerViewItemLongClick != null) {
                mOnRecyclerViewItemLongClick.onItemLongClick(v, event, getAdapterPosition());
            }
            return false;
        }
    }

    class HolderChatReceive extends RecyclerView.ViewHolder implements View.OnLongClickListener {

        TextView tvNickName;
        TextView tvMsgContent;
        LinearLayout layoutChat;
        MotionEvent event;

        public HolderChatReceive(View itemView) {
            super(itemView);
            tvNickName = (TextView) itemView.findViewById(R.id.textview_nick_name);
            tvMsgContent = (TextView) itemView.findViewById(R.id.textview_message);
            layoutChat = (LinearLayout) itemView.findViewById(R.id.layout_message);
            layoutChat.setOnLongClickListener(this);
        }

        @Override
        public boolean onLongClick(View v) {
            if (mOnRecyclerViewItemLongClick != null) {
                mOnRecyclerViewItemLongClick.onItemLongClick(v, event, getAdapterPosition());
            }
            return false;
        }
    }

    /**
     * item点击接口
     */
    public interface OnRecyclerViewItemLongClick {
        void onItemLongClick(View childView, MotionEvent event, int position);
    }
}


ChatMessage消息实体类

package com.alter.popupwindowmenu.model;

/**
 * @CreateDate: 2018/3/9
 * @Author: lzsheng
 * @Description:
 * @Version:
 */
public class ChatMessage {

    private UserInfo userInfo;
    private int from;
    private String msgContent;

    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

    public int getFrom() {
        return from;
    }

    public void setFrom(int from) {
        this.from = from;
    }

    public String getMsgContent() {
        return msgContent;
    }

    public void setMsgContent(String msgContent) {
        this.msgContent = msgContent;
    }

    @Override
    public String toString() {
        return "ChatMessage{" +
                "userInfo=" + userInfo +
                ", from=" + from +
                ", msgContent='" + msgContent + '\'' +
                '}';
    }
}

布局代码:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="50dp"
        >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dp"
            android:layout_toLeftOf="@+id/layout_user"
            android:orientation="vertical"
            >

            <!--<LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:orientation="vertical"
                >

                <TextView
                    android:id="@+id/textview_nick_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="5dp"
                    android:layout_marginRight="15dp"
                    android:gravity="right"
                    android:text="Alter"
                    />
            </LinearLayout>-->

            <LinearLayout
                android:id="@+id/layout_message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/chat_msg_send_bg"
                android:gravity="center"
                android:orientation="vertical"
                >

                <TextView
                    android:id="@+id/textview_message"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_margin="10dp"
                    />
            </LinearLayout>
        </LinearLayout>


        <LinearLayout
            android:id="@+id/layout_user"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:orientation="vertical"
            >

            <ImageView
                android:id="@+id/imageview_pic"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:src="@drawable/user_pic"
                android:scaleType="centerInside"
                />
        </LinearLayout>
    </RelativeLayout>
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="50dp"
        >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_toRightOf="@+id/layout_user"
            android:orientation="vertical"
            >

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:orientation="vertical"
                >

                <TextView
                    android:id="@+id/textview_nick_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="3dp"
                    android:layout_marginLeft="15dp"
                    android:textColor="#898989"
                    android:text="Mia"
                    />
            </LinearLayout>

            <LinearLayout
                android:id="@+id/layout_message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/chat_msg_receive_bg"
                android:gravity="center"
                android:orientation="vertical"
                >

                <TextView
                    android:id="@+id/textview_message"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_margin="10dp"
                    />
            </LinearLayout>
        </LinearLayout>


        <LinearLayout
            android:id="@+id/layout_user"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >

            <ImageView
                android:id="@+id/imageview_pic"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:scaleType="centerCrop"
                android:src="@drawable/girl_pic"
                />
        </LinearLayout>
    </RelativeLayout>
</FrameLayout>


MainActivity的代码:

package com.alter.popupwindowmenu.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.alter.popupwindowmenu.R;
import com.alter.popupwindowmenu.adapter.ChatDetailAdapter;
import com.alter.popupwindowmenu.model.ChatMessage;

import java.util.ArrayList;
import java.util.List;


/**
 * @CreateDate: 2018/3/9
 * @Author: lzsheng
 * @Description:
 * @Version:
 */
public class MainActivity extends Activity {

    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLinearLayoutManager;
    private ChatDetailAdapter mChatDetailAdapter;
    private List<ChatMessage> mChatMessages;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initVariable();
        initViews();
        initData();
        setViewsData();
    }

    private void initVariable() {
        mChatMessages = new ArrayList<>();
    }

    private void initViews() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_messages);
        mLinearLayoutManager = new LinearLayoutManager(MainActivity.this);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
    }

    private void initData() {
        for (int i = 'A'; i <= 'Z'; i++) {
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setFrom((int) (Math.random() * 2) + 1);
//            int s = (int) (Math.random() * ('Z' - 'A' + 1)) + 'A';
//            int e = (int) (Math.random() * ('Z' - 'A' + 1)) + 'A';
            int s = (int) (Math.random() * 120) + 1;
            int e = (int) (Math.random() * 120) + 1;
            Log.d(MainActivity.class.getSimpleName(), "s = " + s);
            Log.d(MainActivity.class.getSimpleName(), "e = " + e);
            int min = 0;
            int max = 0;
            if (s <= e) {
                min = s;
                max = e;
            } else {
                min = e;
                max = s;
            }
            StringBuffer buffer = new StringBuffer();
            for (int j = min; j <= max; j++) {
                int c = (int) (Math.random() * ('Z' - 'A' + 1)) + 'A';
                Log.d(MainActivity.class.getSimpleName(), "c = " + c);
//                buffer.append(String.valueOf((char) (Math.random() * max) + min));
                buffer.append(String.valueOf((char) c));
            }
            chatMessage.setMsgContent(buffer.toString());
            buffer.setLength(0);
            // 或者:
            // buffer.delete(0, buffer.length());
            mChatMessages.add(chatMessage);
            Log.d(MainActivity.class.getSimpleName(), "i = " + i + "\n===========分割线==============");
        }
    }

    private void setViewsData() {
        mChatDetailAdapter = new ChatDetailAdapter(MainActivity.this);
        mChatDetailAdapter.setChatMessages(mChatMessages);
        mRecyclerView.setAdapter(mChatDetailAdapter);
//        mRecyclerView.smoothScrollToPosition(mChatDetailAdapter.getItemCount());
//        mLinearLayoutManager.scrollToPositionWithOffset(mChatDetailAdapter.getItemCount() + 1, 0);
        mRecyclerView.scrollToPosition(mChatDetailAdapter.getItemCount() - 1);
        mChatDetailAdapter.setOnRecyclerViewItemLongClick(new ChatDetailAdapter.OnRecyclerViewItemLongClick() {
            @Override
            public void onItemLongClick(View childView, MotionEvent event, int position) {
                Toast.makeText(MainActivity.this, mChatMessages.get(position).getMsgContent(), Toast.LENGTH_SHORT).show();
            }
        });
    }

}

由于作者水平有限,语言描述及代码实现中难免有纰漏,望各位看官多提宝贵意见!

Hello , World !

感谢所有!








  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

windfallsheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值