recyclerview 数据混乱

recyclerview 数据混乱_第1张图片

如上图,这是我的item layout,这是我的bindView里的代码:

public void bindView(int position) {
            ChatMessage msg = mMsgs.get(position);
            if (msg.getFrom().equals(Constants.PEER)) {
                mReceivedTv.setText(msg.getContent());
                mSenderIv.setVisibility(View.INVISIBLE);
                mSenderTv.setVisibility(View.INVISIBLE);
            } else if (msg.getFrom().equals(Constants.ME)) {
                mSenderTv.setText(msg.getContent());
                mReceivedIv.setVisibility(View.INVISIBLE);
                mReceivedTv.setVisibility(View.INVISIBLE);
            }
        }

感觉代码没问题,结果数据还是混乱了。
解决办法(直接上代码):

public void bindView(int position) {
            ChatMessage msg = mMsgs.get(position);
            if (msg.getFrom().equals(Constants.PEER)) {
                //必须要设置接收信息布局和发送的信息的布局的Visible,否则数据会混乱。
                setVisibility(View.INVISIBLE, View.VISIBLE);
                mReceivedTv.setText(msg.getContent());
            } else if (msg.getFrom().equals(Constants.ME)) {
                setVisibility(View.VISIBLE, View.INVISIBLE);
                mSenderTv.setText(msg.getContent());
            }
//            Log.d(TAG, "bindView: " + msg.getFrom());
        }

        private void setVisibility(int senderVisibility, int receivedVisibility) {
            mSenderIv.setVisibility(senderVisibility);
            mSenderTv.setVisibility(senderVisibility);

            mReceivedIv.setVisibility(receivedVisibility);
            mReceivedTv.setVisibility(receivedVisibility);
        }

说到底,还是RecyclerView的复用机制的问题,抽空好好研究下。

你可能感兴趣的:(Android)