安卓 - SimpleCursorAdapter.ViewBinder - 设置背景颜色

5
我从数据库中检索了我的游泳表现。我想根据它的值更改一个字段的背景颜色。例如,如果我游了4圈,我希望有一种颜色背景。我尝试使用以下代码设置背景,但文字消失了。
        String[] columns = new String[] { "swimm_pos", "swimm_date","swimm_lap", "swimm_stroke", "swimm_time", "swimm_media", "swimm_efficiency", "swimm_note" };
        int[] to = new int[] { R.id.row_counter, R.id.swimm_date, R.id.swimm_lap, R.id.swimm_stroke, R.id.swimm_time, R.id.swimm_medialap, R.id.swimm_efficiency, R.id.swimm_note};

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(
            this, 
            R.layout.contacto_list_item, 
            cursor, 
            columns, 
            to);

        adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
              if (view.getId() == R.id.swimm_lap)
                { 
                  int color = cursor.getInt(columnIndex);
                  String s = String.valueOf(color);
                  if (s.equals("4")) {
                  TextView tv = (TextView)view;
                  tv.setBackgroundColor(0xFF558866);}
                 return true;

            }
              return false;}

        });

当lap等于4时,也可以将另一个字段的背景颜色设置为某个值,例如在我的代码中:R.id.swimm_pos? 谢谢。
2个回答

3

从ViewBinder返回true暗示着您还将数据绑定到视图中。

但在您的情况下,您没有设置R.id.swimm_lap的文本。

因此,在返回语句之前添加setText。

tv.setText(s);
return true;

编辑: 针对第二个问题,假设您想根据游泳圈数更改 R.id.row_counter 的背景,请添加以下内容:
else if (view.getId() == R.id.row_counter){ 
 int color = cursor.getString(cursor.getColumnIndex("swimm_lap")); 
 if (s.equals("4")) {
     view.setBackgroundColor(0xFF558866);
 }
}

谢谢,非常好。至于第二个问题,是否可以添加类似以下的内容:TextView tv = (TextView) findViewById(R.modificacontatto.edswimm_pos); - lucignolo
我编辑了答案,如果你只是改变颜色,可以返回false而不是设置文本,但如果不起作用,你也需要设置文本。 - nandeesh

0
解决了,这是正确的代码:
         adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
              if (view.getId() == R.id.row_counter)
                { 
                  int color = cursor.getInt(cursor.getColumnIndex("swimm_lap"));
                  String s = String.valueOf(color);
                  if (s.equals("4")) {
                  TextView tv = (TextView)view;
                  tv.setBackgroundColor(0xFF558866);
                              }
                 return true;
            }
              return false;}
        });
    this.setListAdapter(adapter);
    datasource.close();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接