android recyclerview:如何以编程方式选择TextView背景色? [英] android recyclerview: how do I programmatically select TextView background color?

查看:165
本文介绍了android recyclerview:如何以编程方式选择TextView背景色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有CardViews的RecyclerView列表.在每个CardView上,用户都从下拉对话框中预先选择了类型".类型选择为工作"和家庭".类型选择作为字符串存储在SQLite数据库中.当我运行该应用程序时,没有显示TextView"cardtype1"的视图,该视图应该显示数据库中的类型选择.

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.

如何为CardView中显示的TextView类型设置不同的背景颜色,具体取决于用户选择的内容以及存储在数据库中的内容?下面是适配器文件中的部分代码.

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"));
    }

推荐答案

当用户从您的两个选项中进行选择时,请使用以下设置来设置textColor.

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"));
    }
}

希望这会有所帮助

这篇关于android recyclerview:如何以编程方式选择TextView背景色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆