java - 使特定 ListView 行背景不同颜色 - Android?

标签 java android listview

我正在从数据库中的数据编译的数组创建一个 ListView 。 数组 1:名字数组(由名字组成) 数组2:lastname数组(由姓氏组成)

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

这是我的代码:

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

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

最佳答案

这真的很简单,只需检查名字是否是约瑟夫即可。像这样的事情:

@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;
}

关于java - 使特定 ListView 行背景不同颜色 - Android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25634586/

相关文章:

安卓的 ListView 。在使 Activity 的 View 无效后更新单元格中的 View

listview - jquery mobile listview在每个项目之间创建空间

java - 服务小程序请求

java - 选择日期、月份和年份 file.lastModified();

android - 抽屉导航切换填充

android - ListView 项目在滚动时随机排列

python - Django 只是按日期对 ListView 进行排序

java - 将应用程序 Controller 添加到 android 项目?

java - 使用javascript将dataURL转换为文件

android - 未声明的标识符 'setfscreation' AOSP