在ListView中更改单元格的背景颜色?

时间:2014-04-09 22:48:34

标签: java android android-studio

我正在尝试根据其中的文本更改列表视图中每个单元格的颜色。这就是我目前填充listview的方式:

    DBHelper db = new DBHelper(this);
    List<HiveEquipment> heList = db.getEquipmentForHive(currentHiveId);
    final ArrayAdapter<HiveEquipment> dataAdapter = new ArrayAdapter<HiveEquipment>(this,
            android.R.layout.simple_list_item_1, heList);
    final ListView equipmentList = (ListView) findViewById(R.id.listView);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            equipmentList.setAdapter(dataAdapter);
        }
    });

所以我只想尝试一些事情,我尝试使用以下方法更改背景颜色:

list.getChildAt(0).setBackgroundColor(Color.BLACK);

这返回了一个空指针。所以我用以下方法检查了孩子的数量:

Log.d(&#34;试验&#34;&#34;&#34 + equipmentList.getChildCount());

但即使它在我的列表视图中显示一个项目,它也会返回0。

任何人都可以帮助我理解为什么这会返回0,以及如何选择每个单元格来改变背景颜色?

1 个答案:

答案 0 :(得分:0)

在访问子视图对象之前,您需要确保填充listView(在UI中显示)。这意味着将创建每个子项视图。在您的情况下,我相信您在将适配器设置为listView后立即尝试获取子项,这就是getChildAt返回null的原因。

因此,使用您的方法,仅在创建列表视图后执行以下代码。

View listViewChildAt = listView.getChildAt(0);
listViewChildAt.setBackgroundColor(Color.BLUE);

其他最佳方法是创建自定义适配器并在getView中设置所需子视图的颜色

@Override
public View getView(int position, View contentView , ViewGroup parent)
{
    String text = getItem(position);

    View row = mContext.getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
    if(text.equalsIgnoreCase("yourText")){
        row.setBackgroundColor(Color.BLUE);
    }
    return row;
}
相关问题