Recycler视图onBindViewHolder正在重复一种奇怪的模式

时间:2016-08-17 15:33:38

标签: android android-studio android-recyclerview

我正在开发一个消息应用程序,它具有滑动选项以静音或锁定对话,当我们按静音或锁定按钮时,小图标显示在Recycler视图项目上,但是当我尝试静音甚至锁定某个消息时它显示该项目上的图标,但每10次计数后图标也会显示在元素上。

例如,如果我将消息锁定在位置1,则位置12处的元素也会显示相同的图标,如果我从第一个位置删除了图标,则也会删除后面位置的图标。任何帮助都会受到高度赞赏,因为我是Android开发新手并且仍在努力学习。

照片:

enter image description here

Recycler查看项目xml

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

<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="80dp"
    android:id="@+id/sample1"
    >
    <!-- Bottom View Start-->

    <LinearLayout
        android:id="@+id/leftWrapper"
        android:layout_width="120dp"
        android:weightSum="1"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <LinearLayout
            android:background="#365cf5"
            android:layout_width="60dp"
            android:weightSum="1"
            android:layout_height="match_parent"
            android:id="@+id/panelArchieve"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/archieve"
                android:src="@drawable/archieve"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginLeft="18dp"
                android:layout_marginTop="27dp"/>

        </LinearLayout>

        <LinearLayout
            android:background="#d20909"
            android:id="@+id/bottom_wrapper"
            android:layout_width="60dp"
            android:weightSum="1"
            android:layout_height="match_parent"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/trash"
                android:src="@drawable/trash"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginLeft="18dp"
                android:layout_marginTop="27dp"/>

        </LinearLayout>


    </LinearLayout>


    <LinearLayout
        android:id="@+id/bottom_wrapper_2"
        android:layout_width="120dp"
        android:weightSum="1"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <LinearLayout
            android:background="#365dea"
            android:layout_width="60dp"
            android:weightSum="1"
            android:layout_height="match_parent"
            android:id="@+id/panelLock"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/lock"
                android:src="@drawable/lock"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginLeft="18dp"
                android:layout_marginTop="27dp"/>

        </LinearLayout>

        <LinearLayout
            android:background="#0e9b04"
            android:layout_width="60dp"
            android:weightSum="1"
            android:id="@+id/panelMute"
            android:layout_height="match_parent"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/mute"
                android:src="@drawable/mute"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginLeft="18dp"
                android:layout_marginTop="27dp"/>

        </LinearLayout>


    </LinearLayout>
    <!-- Bottom View End-->

    <!-- Surface View Start -->
    <LinearLayout
        android:padding="10dp"
        android:background="#303030"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <ImageView android:layout_width="60dp"
                android:layout_height="60dp"
                android:id="@+id/rv_img_name"
                android:src="@drawable/logo"
                android:padding="3dp"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="Small Text"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="9dp"
                android:layout_marginRight="2dp"
                android:id="@+id/rv_title"
                android:textColor="#ffffff"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/rv_img_name"
                android:layout_toEndOf="@+id/rv_img_name"
                android:maxLines="1"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="Small Text"
                android:id="@+id/rv_content"
                android:textColor="#ffffff"
                android:layout_below="@+id/rv_title"
                android:layout_alignLeft="@+id/rv_title"
                android:layout_alignStart="@+id/rv_title"
                android:maxLines="1"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text=""
                android:id="@+id/txtTime"
                android:textColor="#ffffff"
                android:maxLines="1"
                android:layout_alignTop="@+id/rv_title"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true" />

            <ImageView
                android:layout_width="18dp"
                android:layout_height="18dp"
                android:id="@+id/imgMute"
                android:src="@drawable/mute"
                android:padding="2dp"
                android:layout_marginTop="11dp"
                android:layout_toRightOf="@+id/rv_title"


                 />

            <ImageView
                android:layout_width="18dp"
                android:layout_height="18dp"
                android:id="@+id/imgLock"
                android:src="@drawable/lock"
                android:padding="2dp"
                android:layout_marginTop="11dp"
                android:layout_toRightOf="@+id/imgMute" />


        </RelativeLayout>

    </LinearLayout>
    <!-- Surface View End -->
</com.daimajia.swipe.SwipeLayout>

RecyclerViewAdapter

@Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
    //final int position = Texty.position;
    final tblMsgs name = mDataset.get(position);
    viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);
    viewHolder.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
        @Override
        public void onOpen(SwipeLayout layout) {

        }

        @Override
        public void onClose(SwipeLayout layout) {
            viewHolder.btnDel.setTag("trash");
            viewHolder.btnDel.setImageResource(R.drawable.trash);
        }
    });

    //Double click
    viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
        @Override
        public void onDoubleClick(SwipeLayout layout, boolean surface) {
            //Toast.makeText(mContext, "Position: " + position, Toast.LENGTH_SHORT).show();
        }
    });

    //Open conversation.
    viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(viewHolder.swipeLayout.getOpenStatus() == SwipeLayout.Status.Open) {
                mItemManger.closeAllItems();
                viewHolder.btnDel.setTag("trash");
                viewHolder.btnDel.setImageResource(R.drawable.trash);
            }
            else{ //Open conversation
                mItemManger.closeAllItems();
                Toast.makeText(mContext, " onClick : " + position, Toast.LENGTH_SHORT).show();
            }

        }
    });

    //Delete
    viewHolder.panelDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (viewHolder.btnDel.getTag().equals("trash")){
                viewHolder.btnDel.setTag("del");
                viewHolder.btnDel.setImageResource(R.drawable.delete);
                YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.trash));
            }
            else  if (viewHolder.btnDel.getTag().equals("del")){
                viewHolder.btnDel.setTag("trash");
                //viewHolder.btnDel.setImageResource(R.drawable.trash);
                ds.deleteChat(viewHolder.textViewPos.getTag().toString());
                mItemManger.removeShownLayouts(viewHolder.swipeLayout);
                mDataset.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, mDataset.size());
                mItemManger.closeAllItems();
            }
        }
    });


    //Mute/Unmute
    viewHolder.panelMute.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(), "Mute unmute pos: " + position, Toast.LENGTH_SHORT).show();
            if (viewHolder.btnMute.getTag().equals("bell")){
                mItemManger.closeAllItems();
                viewHolder.imgMute.setVisibility(View.GONE);
                viewHolder.btnMute.setTag("mute");
                viewHolder.btnMute.setImageResource(R.drawable.mute);
                ds.unMute(name.getrNumber());
            }
            else{

                //Save Sender Settings
                ds.open();
                if(ds.selectCount_tblSender(name.getrNumber()) ==  0){
                    //Log.i(Log_tag, "Saving settings for " + viewHolder.textViewPos.getTag().toString());
                    tblSender sndr = new tblSender();
                    sndr.setNumber(name.getrNumber());
                    ds.create_tblSender(sndr);
                }

                mItemManger.closeAllItems();
                viewHolder.imgMute.setImageResource(R.drawable.mute);
                viewHolder.imgMute.setVisibility(View.VISIBLE);
                //YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.imgMute));
                viewHolder.btnMute.setTag("bell");
                //YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.mute));
                ds.mute(name.getrNumber());
                viewHolder.btnMute.setImageResource(R.drawable.bell);
            }
            //mItemManger.closeAllItems();
            //Toast.makeText(view.getContext(), "Deleted " + viewHolder.textViewPos.getText().toString() + "!", Toast.LENGTH_SHORT).show();
        }
    });

    //Lock / Unlock
    viewHolder.panelLock.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (viewHolder.btnLock.getTag().equals("locked")){
                //Save Sender Settings
                ds.open();
                if(ds.selectCount_tblSender(viewHolder.textViewPos.getTag().toString()) ==  0){
                    //Log.i(Log_tag, "Saving settings for " + viewHolder.textViewPos.getTag().toString());
                    tblSender sndr = new tblSender();
                    sndr.setNumber(viewHolder.textViewPos.getTag().toString());
                    ds.create_tblSender(sndr);
                }
                mItemManger.closeAllItems();
                viewHolder.imgLock.setImageResource(R.drawable.lock);
                viewHolder.imgLock.setVisibility(View.VISIBLE);
                //YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.imgLock));
                viewHolder.btnLock.setTag("unlocked");
                viewHolder.btnLock.setImageResource(R.drawable.unlock);
                //YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(view.findViewById(R.id.lock));
                ds.Lock(viewHolder.textViewPos.getTag().toString());
            }
            else{
                mItemManger.closeAllItems();
                viewHolder.imgLock.setVisibility(View.GONE);
                viewHolder.btnLock.setTag("locked");
                viewHolder.btnLock.setImageResource(R.drawable.lock);
                ds.unLock(viewHolder.textViewPos.getTag().toString());
            }
            //mItemManger.closeAllItems();
        }
    });

    //Archieve
    viewHolder.panelArchieve.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mDataset.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, mDataset.size());
            mItemManger.closeAllItems();

            ds.open();
            if(ds.selectCount_tblSender(viewHolder.textViewPos.getTag().toString()) ==  0){
                //Log.i(Log_tag, "Saving settings for " + viewHolder.textViewPos.getTag().toString());
                tblSender sndr = new tblSender();
                sndr.setNumber(viewHolder.textViewPos.getTag().toString());
                ds.create_tblSender(sndr);
            }
            ds.archieve(viewHolder.textViewPos.getTag().toString());

        }
    });


    viewHolder.textViewPos.setText(name.getSenderName());
    viewHolder.textViewPos.setTag(name.getrNumber());
    viewHolder.textViewData.setText(name.getMessage().trim());
    //Log.i(Log_tag, "Msg: " +  name.getMessage().trim());
    //viewHolder.txtTime.setText(name.getTime());

    //Time Text
    try {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        Date date = new Date();
        String dateNowStr = formatter.format(date);
        Date dateNow = null;

        dateNow = formatter.parse(dateNowStr);

        String dateSmsStr = name.getTime().substring(0,10);
        Date dateSMS = formatter.parse(dateSmsStr);
        if (dateSMS.compareTo(dateNow)<0)
        {
            viewHolder.txtTime.setText(dateSmsStr.substring(0,10)); // + " " + name.getTime().substring(11,name.getTime().length()));
        }
        else {
            viewHolder.txtTime.setText(name.getTime().substring(11,name.getTime().length()));
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    //ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
    //int colorRandom = generator.getRandomColor(); // generate random color
    //int colorAlpha = generator.getColor(mDataset.get(position).getrName().substring(0,1));//(same key returns the same color)
    // declare the builder object once.
    TextDrawable.IBuilder builder = TextDrawable.builder()
            .beginConfig()
            .withBorder(0)
            .toUpperCase()
            .endConfig()
            .round();

    int greenColorValue = Color.parseColor("#FF457BDF");
    TextDrawable ic1 = builder.build(mDataset.get(position).getrName().substring(0,1), greenColorValue);
    viewHolder.imgName.setImageDrawable(ic1);
    if(ds.select_tblSender(name.getrNumber()).getIsMute() == 1){ //Mute sign
        Log.i(Log_tag, name.getrNumber() + " was muted at position " + position);
        viewHolder.btnMute.setTag("bell");
        viewHolder.btnMute.setImageResource(R.drawable.bell);
        viewHolder.imgMute.setVisibility(View.VISIBLE);
    }
    if(ds.select_tblSender(name.getrNumber()).getIsProtected() == 1){ //Mute sign
        viewHolder.btnLock.setTag("unlocked");
        viewHolder.btnLock.setImageResource(R.drawable.unlock);
        viewHolder.imgLock.setVisibility(View.VISIBLE);
    }
    mItemManger.bindView(viewHolder.itemView, position);
}

MainActivity

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    updateBarHandler = new Handler();


    //Fill Inbox
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    // Layout Managers:
    recyclerView.setLayoutManager(new LinearLayoutManager(this));


    ds = new dataSource(this);
    activity = this;


    mAdapter = new RecyclerViewAdapter(activity, listInboxAll);
    ((RecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);
    recyclerView.setAdapter(mAdapter);
    recyclerView.setOnScrollListener(onScrollListener);


    //All conversations
    GetAllMsgs task = new GetAllMsgs();
    task.execute();
}

GetAllMsgs()

 private class GetAllMsgs extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {
        try {
            ContentResolver contentResolver = getContentResolver();
            final String[] projection = new String[]{"*"};
            Uri uriSMSURI = Uri.parse("content://mms-sms/conversations/");
            Cursor cur = contentResolver.query(uriSMSURI, projection, null, null, "date DESC");
            int i = 0;
            while (cur.moveToNext()) {
                String address = cur.getString(cur.getColumnIndex("address"));
                final String body = cur.getString(cur.getColumnIndexOrThrow("body"));
                final String date = cur.getString(cur.getColumnIndex("date"));
                final Long timestamp = Long.parseLong(date);
                //Log.i(Log_tag, "Msg: " + body + " from: " + address);
                address = address.trim();
                if(address.toString().startsWith("92"))
                {
                    address = address.toString().replace("92", "0");
                }
                else if(address.toString().startsWith("3")){
                    address = "0" + address;
                }
                else if(address.toString().startsWith("+92"))
                {
                    address = address.toString().replace("+92", "0");
                }
                final String nAdd = address;
                time = DateFormat.is24HourFormat(activity);
                if(time){
                    dateFormat = new SimpleDateFormat("dd/MM/yyyy k:mm");
                }
                else{
                    dateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm a");
                }

                String usr = getContactName(activity, nAdd);
                tblMsgs msg = new tblMsgs();
                msg.setMessage(body);
                msg.setSenderName(usr); //Fuzool hai for now
                msg.setIsSent(1);
                msg.setIsReply(0);
                msg.setIsUploaded(0);
                msg.setIsLocked(0);
                msg.setTime(dateFormat.format(timestamp));
                msg.setrName(usr); //Name from phone book
                msg.setrNumber(nAdd);
                msg.setTimeStamp(timestamp);
                //listInboxAll.add(msg);
                Texty.position = i;
                ((RecyclerViewAdapter) mAdapter).addnewItem(msg);
                i++;
                final int j = i;
                if(i % 5 == 0){
                    updateBarHandler.post(new Runnable() {
                        @Override
                        public void run () {
                            ((RecyclerViewAdapter) mAdapter).Update(j);
                            recyclerView.setAdapter(mAdapter);
                            recyclerView.setLayoutManager(new LinearLayoutManager(activity));

                        }
                    });
                }

                //listInboxAll.add(msg);
                //ds.create(msg);
            }
            return "done";
        }
        catch(Exception ex){
            Log.e(Log_tag, ex.getMessage());
            return "failed";
        }
    }

    @Override
    protected void onPostExecute(String result) {



    }
}

1 个答案:

答案 0 :(得分:0)

@Gabe Sechan解决了我的问题,我不得不最初改变图标的​​可见性。