【问题标题】:Make particular listview row background different color - Android?使特定的列表视图行背景颜色不同 - Android?
【发布时间】:2014-09-03 00:51:29
【问题描述】:

我正在从数据库中的数据编译的数组创建一个列表视图。 数组 1:firstnamearray(由名字组成) 数组2:lastnamearray(由姓氏组成)

每个列表视图行都会列出一个名称。例如,如果名字是“Joseph”,我希望该行的背景为绿色。我该怎么做?

这是我的代码:

CustomList adapter = new CustomList(getActivity(), firstnamearray, lastnamearray);

mainListView.setAdapter(adapter);

这是我的 CustomList 适配器:

public class CustomList extends ArrayAdapter<String> {
    private final Activity context;
    private final String[] firstnamearray;
    private final String[] lastnamearray;

    public CustomList(Activity context,
                      String[] firstnamearray, String[] lastnamearray) {
        super(context, R.layout.simplerow, firstnamearray);
        this.context = context;
        this.firstnamearray = firstnamearray;
        this.lastnamearray = lastnamearray;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {

        LayoutInflater inflater = context.getLayoutInflater();
        View rowView= inflater.inflate(R.layout.simplerow, null, true);
        TextView firstname = (TextView) rowView.findViewById(R.id.firstname);
        TextView lastname = (TextView) rowView.findViewById(R.id.lastname);

        cardnumber.setText(firstnamearray[position]);
        expdate.setText(lastnamearray[position]);

        return rowView;
    }
}

我对此进行了研究,并看到一些人谈论在单击或选择时更改背景颜色,但我希望它在创建时具有不同的行颜色(如果名字为“Joseph”)。

【问题讨论】:

    标签: java android listview


    【解决方案1】:

    非常简单,只需检查名称是否为 Joseph。像这样的:

    @Override
    public View getView(int position, View view, ViewGroup parent) {
    
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView= inflater.inflate(R.layout.simplerow, null, true);
        TextView firstname = (TextView) rowView.findViewById(R.id.firstname);
        TextView lastname = (TextView) rowView.findViewById(R.id.lastname);
        if(firstnamearray[position].equels("Joseph")){
        //setbackground color to your desired color
        rowView.setBackgroundColor(context.getResources().getColor(R.color.red));//color defined in xml
        }else{
        rowView.setBackgroundColor(context.getResources().getColor(R.color.white));// your default color
        }
        cardnumber.setText(firstnamearray[position]);
    
        expdate.setText(lastnamearray[position]);
    
        return rowView;
    }
    

    【讨论】:

    • 这适用于滚动吗?我读到了一些关于视图位置随着滚动而变化的内容以及人们在背景颜色转移到不同的列表视图行时遇到的问题
    • @user3794585 当我扩展基本适配器时它不起作用,但您扩展阵列适配器时它可能会起作用。让它工作的万无一失的方法是添加一个 else 子句。请参阅我编辑的答案。
    • 谢谢你应该工作。不敢相信我忽略了这一点
    • @user3794585 很高兴。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    相关资源
    最近更新 更多