简体   繁体   中英

Android Fragment and Adapter issue

I have made a sample chat layout which just adds the EditText input to a RecyclerView, but as you see in this picture after the fifth item it doesn't work the way it shoud (the numbers are the EditText outputs) 在此处输入图像描述

Fragment class =>

Boolean me = true ;
Boolean seen = false ;

@Override
public void onClick(View view) {

   if (view.getId() == R.id.send_button) {
        me = !me ;
        seen = !seen ;
        sendMessage();

    }



}
private void sendMessage(){


    String editTextString = editText.getText().toString() ;

    Calendar calendar = Calendar.getInstance() ;
    String time = calendar.get(Calendar.HOUR) + ":" + calendar.get(Calendar.MINUTE) ;

    first_message.setVisibility(View.GONE);
    if (editTextString.equals("")){
        return;
    }
    E08Object object = new E08Object();
    object.setMessage(editText.getText().toString());
    object.setDate(time);
    object.setMe(me);
    object.setSeen(seen);


    list.add(object) ;
    adapter.notifyDataSetChanged();
    fragment_recyclerView.smoothScrollToPosition(list.size());
    editText.setText("");




}

Adapter class =>

    @Override
public void onBindViewHolder(@NonNull VH holder, int position) {
    holder.textView.setText(list.get(position).getMessage());
    holder.timeTextVIew.setText(list.get(position).getDate());

        if (!list.get(position).getMe()) {
            holder.seenImage.setVisibility(View.GONE);
            holder.fragmentParent.setBackground(ContextCompat.getDrawable(Application.getContext() , R.drawable.person_message_rounded));

        }
}

Please check. You must reset value in else block inside bindViewHolder as the views are recycled.

if (!list.get(position).getMe()) {
  holder.seenImage.setVisibility(View.GONE);
  holder.fragmentParent.setBackground(ContextCompat.getDrawable(Application.getContext() , R.drawable.person_message_rounded));
} else {
  holder.seenImage.setVisibility(View.VISIBLE);
  holder.fragmentParent.setBackground(ContextCompat.getDrawable(Application.getContext() , R.drawable.THE_DEFAULT_DRAWABLE));
}

This should help if this issue is due to recycling. Let me know if this helps. Also, better to attach the item layout and the recycler layout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM