android recyclerview: how do I programmatically se

2020-05-03 10:11发布

I have a RecyclerView list of CardViews. On each CardView, the user previosuly selected the "type" from a dropdown dialog. The type choices are "Work" and "Home". The type choice is stored in an SQLite database as a String. When I run the app, no view is shown for the TextView "cardtype1" which is supposed to show the type choice from the database.

How can I set a different background color for TextView type that is shown on the CardView, depending on what the user selects and is stored in the database? Below is the partial code from the Adapter file.

Adapter.java
...

public List<ListItem> listItems;

private static class ItemHolder extends RecyclerView.ViewHolder {

    private TextView cardType1;

    private ItemHolder(View itemView) {
        super(itemView);

        cardType1 = (TextView) itemView.findViewById(R.id.cardType1);

public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

    final ListItem listItem = listItems.get(position);
    final ItemHolder itemHolder = (ItemHolder) holder;        

    itemHolder.cardType1.setText(listItem.getType());

    if (listItem.getType() == "Work") {
        itemHolder.cardType1.setBackgroundColor(Color.parseColor("#000000"));
    }
    else if (listItem.getType() == "Home") {
        itemHolder.cardType1.setBackgroundColor(Color.parseColor("#008080"));
    }

2条回答
地球回转人心会变
2楼-- · 2020-05-03 10:40

Use the following to set the textColor when user selects from your two option.

public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
    final ListItem listItem = listItems.get(position);
    final ItemHolder itemHolder = (ItemHolder) holder;        
    itemHolder.cardType1.setText(listItem.getType());
    holder.itemView.setOnClickListener(new View.OnClickListener() {
    if (listItem.getType() == "Work") {
       itemHolder.cardType1.setBackgroundColor(Color.parseColor("#000000"));
    }
    else if (listItem.getType() == "Home") {
       itemHolder.cardType1.setBackgroundColor(Color.parseColor("#008080"));
    }
}

Hope this helps

查看更多
三岁会撩人
3楼-- · 2020-05-03 10:45

when user click on the option, update the required object in the list, listItems. Then call notifyDataSetChanged() method in your adapter.

查看更多
登录 后发表回答