当我在RecyclerView中添加Item时,不会调用onBindViewHolder

时间:2016-03-05 13:13:03

标签: android android-recyclerview recycler-adapter quickblox-android

我在做聊天应用程序。我正在使用Recyclerview向用户显示聊天。如果我向Recyclerview添加新项目,我将遇到两个问题。第一个是onBindViewHolder不工作第二个是scrollToPosition不工作。 有时候它正常工作但有时我会一次又一次地遇到这些问题。

这里我添加了RecyclerView的初始化

compile 'com.android.support:recyclerview-v7:23.2.0'

LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        ArrayList<String> as = cd.messagesid(dialog.getDialogId());
        adapter = new ChatAdapter(_activity, cd.messages(dialog.getDialogId()), as);
        recyclerView.setAdapter(adapter);

我在适配器页面中使用以下方法添加新项目。

public void add(QBChatMessage qb) {
        chatMessages.add(qb);
        messageidis.add(qb.getId());
        notifyItemInserted(chatMessages.size() - 1);

    }

我使用以下方法将项目添加到recyclerview并向下滚动Recyclerview。

private void scrollDown() {
    //  messagesContainer.scrollToPosition(adapter.getItemCount() - 1);
    //   messagesContainer.smoothScrollToPosition(adapter.getItemCount() - 1);
    messagesContainer.scrollToPosition(adapter.getItemCount() - 1);
}

 Boolean cc = cd.Insert_tbl_chathistory(msg.getDialogId(), msg.getSenderId() + "", msg.getBody(), msg.getId() + "", msg.getDateSent(), "", msg.getReadIds() + "", msg.getDeliveredIds() + "", msg.getRecipientId() + "", 1, 0, "");
            if (cc) {
                msg.setProperty("SenderID", msg.getSenderId() + "");

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.add(msg);
                        scrollDown();
                    }
                });
            }

它是我的活动xml文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:fitsSystemWindows="true">


    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            app:navigationContentDescription="@string/abc_action_bar_up_description"
            app:navigationIcon="?attr/homeAsUpIndicator"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">


            <com.chatapp.contacts.CircleImageView
                android:id="@+id/usericon"
                android:layout_width="?attr/actionBarSize"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/colorPrimary"
                android:src="@drawable/ic_profile" />

            <com.chatapp.widgets.MaterialRippleLayout
                style="@style/RippleStyle"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_vertical"
                android:layout_toRightOf="@+id/usericon"
                android:focusable="false"
                android:gravity="center_vertical"
                app:rippleColor="@color/main_color_grey_400">


                <RelativeLayout
                    android:id="@+id/chat_details"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical"
                    android:gravity="center_vertical"
                    android:paddingRight="5dp">

                    <com.chatapp.font.RobotoTextView
                        android:id="@+id/toolbar_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="@dimen/margin_middle"

                        android:minWidth="122dp"
                        android:paddingBottom="@dimen/cpb_stroke_width"
                        android:text=""
                        android:textAppearance="?android:textAppearanceMedium"
                        android:textColor="@color/white" />

                    <com.chatapp.font.RobotoTextView
                        android:id="@+id/toolbar_typing"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/toolbar_title"
                        android:layout_marginLeft="@dimen/margin_middle"
                        android:minWidth="122dp"
                        android:text=""
                        android:textColor="@color/white" />
                </RelativeLayout>
            </com.pluggdd.corporate.chatapp.widgets.MaterialRippleLayout>

        </android.support.v7.widget.Toolbar>

        <vc908.stickerfactory.ui.view.KeyboardHandleRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/sizeNotifierLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <RelativeLayout
                android:id="@+id/container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <RelativeLayout
                    android:id="@+id/bottom"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:background="#fff">

                    <com.chatapp.font.RobotoEditText
                        android:id="@+id/messageEdit"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_above="@+id/sticker_image"
                        android:layout_alignTop="@+id/sticker_image"
                        android:background="#fff"
                        android:hint=" Message text"
                        android:inputType="textMultiLine|textCapSentences"
                        android:maxLines="6"
                        android:paddingBottom="10dp"
                        android:paddingLeft="5dp"
                        android:scrollbars="vertical" />

                    <android.support.design.widget.FloatingActionButton
                        android:id="@+id/chatSendButton"
                        style="@style/Fabsend"
                        android:layout_alignParentRight="true"
                        android:layout_below="@+id/messageEdit"
                        android:layout_marginBottom="3dp"
                        android:layout_marginRight="10dp"
                        app:layout_anchor="@+id/container" />

                    <ImageView
                        android:id="@+id/stickers_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@+id/chatSendButton"
                        android:layout_alignParentLeft="true"
                        android:layout_alignTop="@+id/chatSendButton"
                        android:layout_below="@+id/messageEdit"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:src="@drawable/smile_icon_24p"
                        android:tint="@color/colorPrimary" />

                    <ImageView
                        android:id="@+id/attach_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@+id/chatSendButton"
                        android:layout_alignTop="@+id/chatSendButton"
                        android:layout_below="@+id/messageEdit"
                        android:layout_toRightOf="@+id/stickers_button"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:src="@drawable/imageshare_icon_24p"
                        android:tint="@color/colorPrimary" />

                    <ImageView
                        android:id="@+id/videoshare_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@+id/chatSendButton"
                        android:layout_alignTop="@+id/chatSendButton"
                        android:layout_below="@+id/messageEdit"
                        android:layout_toRightOf="@+id/attach_button"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:src="@drawable/video_icon_24p"
                        android:tint="@color/colorPrimary" />

                    <ImageView
                        android:id="@+id/loc_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignBottom="@+id/chatSendButton"
                        android:layout_alignTop="@+id/chatSendButton"
                        android:layout_below="@+id/messageEdit"
                        android:layout_toRightOf="@+id/videoshare_button"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:src="@drawable/location_icon_24p"
                        android:tint="@color/colorPrimary" />
                </RelativeLayout>

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/messagesContainer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_above="@+id/bottom"
                    android:layout_alignParentLeft="false"
                    android:layout_alignParentTop="false"
                    android:background="@android:color/transparent"
                    android:divider="@null"
                    android:listSelector="@android:color/transparent"
                    android:stackFromBottom="true"
                    android:transcriptMode="alwaysScroll"/>


            </RelativeLayout>

            <FrameLayout
                android:id="@+id/frame"
                android:layout_width="match_parent"
                android:layout_height="240dp"
                android:layout_alignParentBottom="true" />
        </vc908.stickerfactory.ui.view.KeyboardHandleRelativeLayout>
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

这里我添加了我的适配器xml文件

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toplayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:orientation="vertical">

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

        <TextView
            android:id="@+id/txtInfo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:background="@drawable/roundedcornermsg"
            android:gravity="center"
            android:textColor="@android:color/white" />

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">


            <LinearLayout
                android:id="@+id/content"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:orientation="horizontal"
                android:weightSum="100">

                <TextView
                    android:id="@+id/front"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="20" />

                <LinearLayout
                    android:id="@+id/contentWithBackground"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:layout_weight="80"
                    android:background="@drawable/redchat"
                    android:orientation="vertical">

                    <com.chatapp.font.RobotoTextView
                        android:id="@+id/personname"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:paddingLeft="5dp"
                        android:paddingTop="5dp"
                        android:singleLine="true"
                        android:text="Mathankumar:"
                        android:textColor="@color/colorPrimary" />

                    <TextView
                        android:id="@+id/txtMessage"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:autoLink="all"
                        android:minWidth="150dp"
                        android:paddingLeft="10dp"
                        android:textColor="@android:color/white" />

                    <RelativeLayout
                        android:id="@+id/chat_detnot"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:minWidth="160dp"
                        android:visibility="gone">

                        <ImageView
                            android:id="@+id/sticker_image"
                            android:layout_width="160dp"
                            android:layout_height="160dp"
                            android:layout_gravity="left"
                            android:autoLink="all" />

                    </RelativeLayout>

                    <RelativeLayout
                        android:id="@+id/chat_det"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:minWidth="160dp"
                        android:visibility="gone">

                        <com.chatapp.widgets.SquareImageView
                            android:id="@+id/imgView"
                            android:layout_width="200dp"
                            android:layout_height="200dp"
                            android:layout_alignParentLeft="true"
                            android:layout_gravity="left"
                            android:autoLink="all"
                            android:scaleType="centerCrop" />

                        <com.chatapp.circularprogressbar.CircularProgressButton
                            android:id="@+id/circular_progress_bar_1"
                            style="@style/CircularProgressBarStyle.3"
                            android:layout_centerInParent="true" />
                    </RelativeLayout>

                    <RelativeLayout
                        android:id="@+id/rlayouts"
                        android:layout_width="match_parent"
                        android:layout_height="20dp"
                        android:background="#80000000"
                        android:gravity="center_vertical"
                        android:minWidth="160dp">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:gravity="right|center_vertical"
                            android:layout_alignParentRight="true">

                            <TextView
                                android:id="@+id/time"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:gravity="center_vertical"
                                android:text="12.32"
                                android:textColor="@color/white"
                                android:paddingRight="@dimen/spacing_medium"
                                android:textSize="10dp" />

                            <ImageView
                                android:id="@+id/msgstatus"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_alignBottom="@+id/time"
                                android:layout_alignTop="@+id/time"
                                android:src="@drawable/ic_eye_icon_unread"
                                android:visibility="visible" />
                        </LinearLayout>
                    </RelativeLayout>

                </LinearLayout>

            </LinearLayout>

        </RelativeLayout>
    </LinearLayout>

</FrameLayout>

这里我添加了我的适配器Java文件

 public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.MyViewHolder> implements View.OnClickListener, Target {

   //Initialisation for objects

        public QBChatMessage getItem(int position) {
            if (chatMessages != null) {
                return chatMessages.get(position);
            } else {
                return null;
            }
        }

        public Float imagefloatsize;
        public int Imageintsize;


        public ChatAdapter(ChatActivity context, List<QBChatMessage> chatMessages, ArrayList<String> val) {
            this.context = context;
            this.chatMessages = chatMessages;
            messageidis = val;
            blurTransformation = new BlurTransformation(context, BLUR_RADIUS);
            mRequestQueue = Volley.newRequestQueue(context);
            baseurl = context.getString(R.string.baseurl);
            downloadurl = context.getString(R.string.downloadlink);
            appname = context.getString(R.string.app_name);
            //This Declaration is used to show the Application Crash Reports for Android
            Thread.setDefaultUncaughtExceptionHandler(new ACRA_Page(context));
            imagefloatsize = convertDpToPixel(200, context);
            Imageintsize = Math.round(imagefloatsize);
        }


        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int position) {

            return new MyViewHolder(LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.chat_rv_adapter, parent, false), isFile(getItem(position).getBody()));


        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            QBChatMessage chatMessage = getItem(position);

            final MyViewHolder vs = holder;
            String Showmsg = chatMessage.getProperty("showmsg").toString();
            // int SenderID = Integer.parseInt(chatMessage.getProperty("SenderID").toString());
            senderID = chatMessage.getProperty("SenderID").toString();
            String val[] = Showmsg.split("Mathan%nahtam&idhaya");
            holder.personame.setTag("" + position);
            String sz = val[0];
            boolean isOutgoing = false;

            if (sz.equalsIgnoreCase("1") || senderID == null || senderID.equals(userid + "")) {
                isOutgoing = true;
            } else {
                isOutgoing = false;
            }
            lastPosition = position;
            //  isOutgoing = chatMessage.getSenderId() == null || chatMessage.getSenderId().equals(currentUser.getId());
            setAlignment(holder, isOutgoing, chatMessage);
            holder.rlayouts.setTag(chatMessage);
            holder.txt_undotext.setTextSize(10);
            holder.txt_undoappicon_48.setTextSize(15);
            holder.txt_delete.setTextSize(15);
            holder.txtMessage.setText(Html.fromHtml("" + chatMessage.getBody() + ""
            ));
            holder.time.setTag("1");
            holder.circular_progress_bar_1.setVisibility(View.GONE);
            holder.time.setText(Html.fromHtml("<small>" + getTimeText(chatMessage)
            ));
            String s = getDateText(chatMessage);
            if (position == 0) {
                holder.txtInfo.setVisibility(View.VISIBLE);
                holder.txtInfo.setText(Html.fromHtml("<small>" + s
                ));
            } else {

            }

        }


        private void setAlignment(MyViewHolder holder, boolean isOutgoing, final QBChatMessage qb) {
            if (isOutgoing) {
                if (isFile(qb.getBody())) {
                        holder.contentWithBG.setBackgroundResource(R.drawable.bluechat);
                        layoutParams = (LinearLayout.LayoutParams) holder.chat_det.getLayoutParams();
                        layoutParams.gravity = Gravity.LEFT;
                        holder.chat_det.setLayoutParams(layoutParams);
                        holder.time.setTextColor(Color.parseColor("#ffffff"));
                } else {
                    holder.contentWithBG.setBackgroundResource(R.drawable.bluechat);
                    layoutParams = (LinearLayout.LayoutParams) holder.txtMessage.getLayoutParams();
                    layoutParams.gravity = Gravity.LEFT;
                    holder.contentWithBG.setMinimumWidth(160);
                    holder.txtMessage.setLayoutParams(layoutParams);
                    holder.txtMessage.setTextColor(Color.parseColor("#ffffff"));
                    holder.time.setTextColor(Color.parseColor("#ffffff"));
                }
            } else {
                if (context.dialog.getType().equals(QBDialogType.GROUP)) {
                    holder.personame.setVisibility(View.VISIBLE);
                    if (name.equals("#@Unknown*&%*")) {
                        QBUser user = ChatService.getInstance().getDialogsUsers().get(Integer.parseInt(senderID));
                        holder.personame.setText("" + user.getLogin().replace(ChatActivity.loginprefix, "") + " :");
                    } else {
                        holder.personame.setText("" + name + " :");
                    }
                } else {
                    if (qb.getReadIds().size() > 0) {
                        PrivateChatImpl.readstatus(qb);
                        holder.personame.setVisibility(View.GONE);
                        holder.contentWithBG.setBackgroundResource(R.drawable.whitechat);
                        layoutParams = (LinearLayout.LayoutParams) holder.chat_det.getLayoutParams();
                        layoutParams.gravity = Gravity.LEFT;
                        holder.chat_det.setLayoutParams(layoutParams);
                        holder.time.setTextColor(Color.parseColor("#ffffff"));

                    } else {
                        holder.contentWithBG.setMinimumWidth(160);
                        holder.contentWithBG.setBackgroundResource(R.drawable.whitechat);
                        layoutParams = (LinearLayout.LayoutParams) holder.txtMessage.getLayoutParams();
                        layoutParams.gravity = Gravity.LEFT;
                        layoutParams.setMargins(5, 0, 0, 0);
                        holder.txtMessage.setLayoutParams(layoutParams);
                        holder.txtMessage.setTextColor(Color.parseColor("#000000"));
                        holder.time.setTextColor(Color.parseColor("#000000"));
                    }
                }
            }
        }

        @Override
        public int getItemCount() {
            return chatMessages.size();
        }

        public void remove(int position) {
            chatMessages.remove(position);
            messageidis.remove(position);
            notifyItemRemoved(position);
        }

        public void add(QBChatMessage qb) {
            chatMessages.add(qb);
            messageidis.add(qb.getId());
            notifyItemInserted(chatMessages.size() - 1);
            //  notifyDataSetChanged();
        }


        static class MyViewHolder extends RecyclerView.ViewHolder {

            public TextView txtMessage, txtInfo, front, time;
            public LinearLayout content;
            public LinearLayout contentWithBG;
            public ImageView msgstatus;
            public ImageView sticker_image;
            public SquareImageView NimgView;
            public RobotoTextView personame, txt_undotext, txt_delete;
            public CircularProgressButton circular_progress_bar_1;
            public RelativeLayout rlayouts, chat_det, chat_detnot;
            public MaterialDesignIconsTextView txt_undoappicon_48;
            public FrameLayout toplayout;

            MyViewHolder(View v, Boolean s) {
                super(v);
    //Initialization for these objects
            }
        }

        @Override
        public void onClick(View v) {
            MyViewHolder holder1 = (MyViewHolder) v.getTag();
            //Access the Textview from holder1 like below
            int id = v.getId();

        }


    }

能否请您解决这些问题。

0 个答案:

没有答案