0

When i choose an item from listview, it turns gray but when I select another item in the listview then the previous highlighted item turns to default color and the new item turns to gray. What I want is to stay both of them to be highlighted, and when a click on the highlighted items they should turn back to normal as well.

My code:

listView = (ListView) findViewById(R.id.conversationList);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new conversationsMultipleChoiceListener());
listView.setAdapter(conversationsAdapter);
((ConversationsAdapter) conversationsAdapter).updateConversations(conversationsList);
listView.setLongClickable(true);
listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
        Conversation item = (Conversation) conversationsAdapter.getItem(position);
        startChat(item, false);
    }
});


private class conversationsMultipleChoiceListener implements ListView.MultiChoiceModeListener {
    @Override
    public void onItemCheckedStateChanged(android.view.ActionMode mode, int position, long id, boolean checked) {
        final int checkedCount = listView.getCheckedItemCount();




        switch (checkedCount) {
            case 0:
                mode.setSubtitle(null);
                break;
            default:
                mode.setSubtitle("" + checkedCount + " konuşma seçildi");
                break;
        }
    }

    @Override
    public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.conversation_actions, menu);
        mode.setTitle("Konuşmalarınız");
        return true;
    }

    @Override
    public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
        return false;
    }

    @Override
    public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {

        switch (item.getItemId()) {
            case R.id.sil:
                Log.w("action","sil");
                mode.finish();
                break;
            case R.id.blokla:
                Log.w("action","blokla");
                mode.finish();
                break;
            default:
                break;
        }

        return true;
    }

    @Override
    public void onDestroyActionMode(android.view.ActionMode mode) {

    }
}

Adapter:

static class ViewHolder {
    TextView nameView;
    TextView bioView;
    CircleImageView imageView;
    TextView badge;
    ProgressBar idleTimeBar;
    public ImageView eyeView;
    ImageView instagramVerified;
    RelativeLayout badgeBg;
    ImageView solOk;
    TextView tarihText;
    ImageView fotoIcon;
    ImageView sesIcon;
}


public static class ConversationsAdapter extends BaseAdapter {
    List<Conversation> conversations;
    LayoutInflater inflater;
    Context context;

    private ConversationsAdapter(Context context, List<Conversation> conversations) {
        this.conversations = conversations;
        this.inflater = LayoutInflater.from(context);
        this.context = context;
    }

    public void updateConversations(List<Conversation> conversations) {
        this.conversations = conversations;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return conversations.size();
    }

    @Override
    public Conversation getItem(int position) {
        return conversations.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.conversation_bars_v2, parent, false);
            holder = new ViewHolder();
            holder.nameView = (TextView) convertView.findViewById(R.id.nameText);
            holder.badge = (TextView) convertView.findViewById(R.id.unreadMessageCount);
            holder.bioView = (TextView) convertView.findViewById(R.id.bioText);
            holder.imageView = (CircleImageView) convertView.findViewById(R.id.image);
            holder.badgeBg = (RelativeLayout) convertView.findViewById(R.id.unreadMessageBg);
            holder.solOk = (ImageView) convertView.findViewById(R.id.imageView22);
            holder.tarihText = (TextView) convertView.findViewById(R.id.textView16);
            holder.sesIcon = (ImageView) convertView.findViewById(R.id.imageView22);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Conversation item = conversations.get(position);
        String name = item.getName();
        String image_url = "http://application.domain.com/photos/profile/main/" + item.getPicture();

        if (item.getLastMessage().equals("Fotoğraf")) {
            holder.sesIcon.setImageResource(R.drawable.send_photo);
            holder.sesIcon.setVisibility(View.VISIBLE);
        }else if (item.getLastMessage().equals("Ses")) {
            holder.sesIcon.setImageResource(R.drawable.send_voice_record);
            holder.sesIcon.setVisibility(View.VISIBLE);
        }else{
            holder.sesIcon.setVisibility(View.INVISIBLE);
        }

        Long messageTimestamp = item.getLastMessageTime();

        long nowTimestamp = timeHolder.toMillis(false);


        Calendar messageTimeCal = Calendar.getInstance();
        Calendar currentTimeCal = Calendar.getInstance();
        messageTimeCal.setTimeInMillis(messageTimestamp);
        currentTimeCal.setTimeInMillis(nowTimestamp);

        boolean sameDay = messageTimeCal.get(Calendar.DAY_OF_YEAR) == currentTimeCal.get(Calendar.DAY_OF_YEAR) &&
                messageTimeCal.get(Calendar.YEAR) == currentTimeCal.get(Calendar.YEAR);

        boolean lastDay = messageTimeCal.get(Calendar.DAY_OF_YEAR) == currentTimeCal.get(Calendar.DAY_OF_YEAR) -1 &&
                messageTimeCal.get(Calendar.YEAR) == currentTimeCal.get(Calendar.YEAR);


        String dateText = "";
        if (sameDay) {
            //Mesaj bugün mü gönderildi?
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("HH:mm");
            dateText = dateFormat1.format(messageTimeCal.getTime());
        }else{
            if (lastDay) {
                //Bugün değilse mesaj dün mü gönderilmiş?
                dateText = "Dün";
            }else{
                //Dün de değilse kaç gün önce gönderilmiş?
                long diff = Math.abs(nowTimestamp - messageTimestamp);
                int bolum =  (int) (diff / (24 * 60  * 60 * 1000));
                if (bolum <= 3) {
                    //Eğer geçen gün sayısı 3 veya daha az ise gün adını ekrana yaz
                    dateText = String.format("%tA", messageTimeCal);
                }else{
                    //Yoksa direk tarihi yaz
                    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
                    dateText = dateFormat.format(messageTimeCal.getTime());
                }
            }
        }




        holder.tarihText.setText(dateText);


        holder.nameView.setText(name);
        if (item.getLastMessageFromMe() == 0) {
            holder.bioView.setTextColor(Color.parseColor("#7A7A7A"));
            //holder.solOk.setColorFilter(Color.parseColor("#666666"), android.graphics.PorterDuff.Mode.MULTIPLY); -- mehmet değiştirdi
            holder.bioView.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL);
        } else {
            holder.bioView.setTextColor(Color.parseColor("#7A7A7A"));
            //holder.solOk.setColorFilter(Color.parseColor("#A8A8B7"), android.graphics.PorterDuff.Mode.MULTIPLY); -- mehmet değiştirdi
            holder.bioView.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL);
        }
        holder.bioView.setText(item.getLastMessage());
        if (item.getLastMessage().equals("")) {
            holder.bioView.setVisibility(View.GONE);
        } else {
            holder.bioView.setVisibility(View.VISIBLE);
        }

        if (item.getPicture().equals("default.jpg")) {
            Picasso.with(context).load(R.drawable.default_picture).into(holder.imageView);
        }else if (item.getPicture().equals("default_1.jpg")) {
            Picasso.with(context).load(R.drawable.default_color_1).into(holder.imageView);
        }else if (item.getPicture().equals("default_2.jpg")) {
            Picasso.with(context).load(R.drawable.default_color_2).into(holder.imageView);
        }else if (item.getPicture().equals("default_3.jpg")) {
            Picasso.with(context).load(R.drawable.default_color_3).into(holder.imageView);
        }else if (item.getPicture().equals("default_4.jpg")) {
            Picasso.with(context).load(R.drawable.default_color_4).into(holder.imageView);
        }else if (item.getPicture().equals("default_5.jpg")) {
            Picasso.with(context).load(R.drawable.default_color_5).into(holder.imageView);
        }else{
            Picasso.with(context).load(image_url).into(holder.imageView);
        }

        holder.badge.setText(String.valueOf(item.getUnread()));
        if (item.getUnread() != 0) {
            holder.badgeBg.setVisibility(View.VISIBLE);
        } else {
            holder.badgeBg.setVisibility(View.GONE);
        }
        return convertView;
    }
}

Listview xml:

<ListView
    android:id="@+id/conversationList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="0dp"
    android:layout_marginRight="10dp"
    android:divider="@android:color/transparent"
    android:dividerHeight="7.0sp"
    android:scrollbars="none"
    android:listSelector="@drawable/conversations_selector"></ListView>

How can i achive that functionality?

Tolgay Toklar
  • 4,151
  • 8
  • 43
  • 73
  • Can you add the `ConversationAdapter` class? At least `ViewHolder`, `onCreateViewHolder()` and `onBindViewHolder()` . I can be more precise if you do so. The idea is to add a field in the `ViewHolder` that says "the item is now selected"! If you post that part I can answer more precisely :-) – A. Wolf Oct 17 '18 at 09:06
  • 1
    @A.Wolf see my edit please :) – Tolgay Toklar Oct 17 '18 at 09:10
  • Thank you for your edit! Now I'm at work, I can't answer in a good way right now, I'm sorry. I'll post a correct answer in the afternoon or this evening :) The idea is dealing with `RecyclerView`. I will post the code as complete as possible, now I can't try it to be sure it works in the proper way. – A. Wolf Oct 17 '18 at 09:25
  • Ok, thank you so much. I am waiting your code :) – Tolgay Toklar Oct 17 '18 at 09:29
  • 1
    Your welcome! I would answer right now, but I can't :-P – A. Wolf Oct 17 '18 at 09:33
  • Unfortunately I can't test the code this evening; I provide you a possible solution (I don't know if works or not, I'm sorry). In the next days I will try to improve it, because I know it's not enough specific. Probably I will ask you more details to understand what behaviour you want. I wish that the answer can help you a little bit in the meanwhile :) – A. Wolf Oct 17 '18 at 18:57

1 Answers1

0

First, add a field conversationSelected in the Conversation class.
You should useRecyclerView instead of ListView.
You can refer to the official documentation to get started with RecyclerView.
When you have your RecyclerView, you can define the Adapter in this way:

public class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ViewHolder> {
List<Conversation> conversations;

public ConversationAdapter(List<Conversation> conversations) {
    this.conversations = conversations; 
}

public ConversationAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
    // create a new view
    TextView v = (TextView) LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_view, parent, false);
    ...
    MyViewHolder vh = new MyViewHolder(v);
    return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Conversation conversation = conversations.get(position);
holder.mTextView.setText(conversation.getConversationText());   

}

// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
    return conversations.size();
}

public static class MyViewHolder extends RecyclerView.ViewHolder {
    // each data item is just a string in this case
    public TextView mTextView;

    public MyViewHolder(TextView v) {
        super(v);
        mTextView = v;
    }
}

Next step: add item click listener to the RecyclerView: I struggled a little bit before see this answer which helps me to solve the problem: RecyclerView click Listener
In the clickListener you have to change the state conversationSelected of the Conversation in the conversations list (not inside the ViewHolder) to true.
Then when you need to retrieve the selected conversation you have only to check this value.

A. Wolf
  • 1,309
  • 17
  • 39