2

嗨,我相当了解编程,但这里的问题是我正在解析来自 json 的数据。因此,我的目标是根据以下条件设置每一行的背景颜色:

Dog 或 Cat 或 Elephant 或 Rhino 或 Lion 它们各自的列表视图背景颜色应为蓝色、红色、黄色、绿色

       {
        "pets" : {
          "dog_id"   : 1,
          "dog_name" : "Dave",
          "cat_id"   : 2,
          "cat_name" : "Prudie"
            "elephant_id" : 3,
            "elephant_name" : "Poncho",
            "lion_id ": 4
            "lion_name" : "King"

        }
      }

请帮忙,我可以解析这个 JSON,但我希望 listView 显示不同的颜色。到目前为止,我可以更改 listView 的整个背景,每个项目的文本,但未能有条件地执行行颜色。

4

5 回答 5

2

你必须

1. Create a custom adapter class
2. With custom adapter, you will create custom view for each row,
3. In getView method of adapter you can change background color as you wish, just like you did to listView.
于 2014-11-14T07:06:16.827 回答
1

正如其他人所解释的那样,它相当简单。但是,请记住,当视图被回收时,背景不会自动恢复为默认颜色。您必须将背景颜色设置为透明或您想要的任何颜色。要做到这一点,简单if else的语句就足够了。很容易忘记这一点,很难弄清楚为什么你会得到错误的颜色。

于 2014-11-14T07:24:49.550 回答
0

您必须使用自定义适配器

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // assumed pet_name holds your string to check
        // Then set color according to your requirement
        if(pet_nane.equalsIgnoreCase("dog"))
        {
            convertView.setBackgroundColor(android.R.color.black);
        }else if(pet_nane.equalsIgnoreCase("cat"))
        {
            convertView.setBackgroundColor(android.R.color.white);
        }
        else{
            convertView.setBackgroundColor(android.R.color.transparent);
        }
        return convertView;
    }
于 2014-11-14T07:12:01.180 回答
0

谢谢大家,

我知道它工作正常,我使用了宠物的 ID

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

        Pets petId = getItem(position);

        if(petId.dog_id == 1)
        {
            convertView.setBackgroundColor(Color.BLUE);
        }else if(petId.cat_id == 2)
        {
            convertView.setBackgroundColor(Color.RED);
        }
        }else if(petId.elephant_id == 3)
        {
            convertView.setBackgroundColor(Color.YELLOW);
        }
        }else if(petId.lion_id == 4)
        {
            convertView.setBackgroundColor(Color.GREEN);
        }
        else{
            convertView.setBackgroundColor(Color.WHITE);
        }
        return convertView;
    }
于 2014-11-14T08:48:49.320 回答
0

您需要创建自定义适配器类。

使用以下方法更改getView方法:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    TextView textView = (TextView) view.findViewById(R.id.textView);
    if(textView.getText().toString().equalsIgnoreCase("elephant"))  //condition to check its text
    {
        //set color to blue
    }
    else if(textView.getText().toString().equalsIgnoreCase("lion"))
    {
        //set color to brown
    }
    return view;
}

希望能帮助到你。

于 2014-11-14T07:09:45.507 回答