Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextDrawable - Display color based on a key (email, id)

I have an issue when using TextDrawable - I want to display the same color for the same user - int color2 = generator.getColor("[email protected]");, in my case using the userId as a key, but instead what I get is same color for all userId's. I tried this in both ListView and now in RecyclerView, but always the same results - all of my contacts share the same color.

This is the code from my ContactsAdapter:

@Override
public void onBindViewHolder(ContactsAdapter.ContactsViewHolder holder, int position) {
    Contact contact = contactList.get(position);

    holder.userName.setText(contact.getUserName());

    TextDrawable.IBuilder builder = TextDrawable.builder()
            .beginConfig()
            .withBorder(0)
            .toUpperCase()
            .endConfig()
            .round();
    ColorGenerator generator = ColorGenerator.MATERIAL;
    // generate random color
    int color1 = generator.getRandomColor();                                    
    // generate color based on a key (same key returns the same color), useful for list/grid views
    int color2 = generator.getColor(holder.getItemId());
    //int color2 = generator.getColor("[email protected]");
    TextDrawable textDrawable = builder.build(contactList.get(position).getUserName().substring(0,1), color2);

    holder.thumbNail.setImageDrawable(textDrawable);
}

If I use int color2 = generator.getColor(holder.userName); I get different colors for the same name, and if I use int color2 = generator.getColor(holder.getItemId()); I get same colors for every userId.

like image 521
Banana Avatar asked Dec 12 '25 13:12

Banana


1 Answers

If I understand the question correctly, when you uncomment int color2 = generator.getColor("[email protected]"); line you expect the same user have the same color, but other users have other colors.

generator.getColor("some_example_string") will constantly return the same color for every user in your list. I see you have copy-pasted that from the github and you expect it to work for you. Pay attention to the previous line of the author:

// generate color based on a key

You have to provide a key, and based on that key a color will be generated. Assuming your user's name may be considered as key, you can perform:

generator.getColor(user.getName()); // e.g. "John Doe"

Now each time the same color will be generated for John Doe and a different color for other users.

like image 120
azizbekian Avatar answered Dec 15 '25 02:12

azizbekian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!