我在使用 TextDrawable 时遇到问题- 我想为同一用户显示相同的颜色 - int color2 = generator.getColor("user@gmail.com");
,在我的例子中使用 userId
作为键,但我得到的是所有 userId
的相同颜色。我在 ListView 和 RecyclerView 中都试过了,但结果总是一样的——我所有的联系人都使用相同的颜色。
这是来 self 的 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("user@gmail.com");
TextDrawable textDrawable = builder.build(contactList.get(position).getUserName().substring(0,1), color2);
holder.thumbNail.setImageDrawable(textDrawable);
}
如果我使用 int color2 = generator.getColor(holder.userName);
我会为同一个名字得到不同的颜色,如果我使用 int color2 = generator.getColor(holder. getItemId());
我为每个 userId 获得相同的颜色。
最佳答案
如果我正确理解了这个问题,当您取消注释 int color2 = generator.getColor("user@gmail.com");
行时,您希望同一用户具有相同的颜色,但其他用户有其他颜色。
generator.getColor("some_example_string")
将不断为列表中的每个用户返回相同的颜色。我看到你已经从 github 上复制粘贴了它,你希望它对你有用。注意作者的前一行:
// generate color based on a key
您必须提供一个键,然后将根据该键生成一种颜色。假设您的用户名可能被视为 key ,您可以执行:
generator.getColor(user.getName()); // e.g. "John Doe"
现在每次都会为 John Doe
生成相同的颜色,为其他用户生成不同的颜色。
关于java - TextDrawable - 根据键(电子邮件、id)显示颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42810657/