Android,使用 SimpleCursorAdapter 设置颜色而不仅仅是字符串

编程入门 行业动态 更新时间:2024-10-26 02:37:21
本文介绍了Android,使用 SimpleCursorAdapter 设置颜色而不仅仅是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在我的应用程序的列表中设置了一个简单的游标适配器,如下所示:

I have a simple cursor adapter set on a list in my application as follows:

private static final String fields[] = {"GenreLabel", "Colour", BaseColumns._ID}; datasource = new SimpleCursorAdapter(this, R.layout.row, data, fields, new int[]{R.id.genreBox, R.id.colourBox});

R.layout.row 由两个 TextViews(genreBox 和 colourBox)组成.与其将 TextView 的内容设置为 "Colour" 的值,不如将其背景色设置为该值.

R.layout.row consists of two TextViews (genreBox and colourBox). Rather than setting the content of the TextView to the value of "Colour" , I would like to set its background colour to that value.

我需要做什么来实现这一目标?

What would I need to do to achieve this?

推荐答案

查看 SimpleCursorAdapter.ViewBinder.

setViewValue 基本上是您对 Cursor 中的数据做任何您想做的事情的机会,包括设置视图的背景颜色.

setViewValue is basically your chance to do whatever you wish with the data in your Cursor, including setting the background color of your views.

例如,类似于:

SimpleCursorAdapter.ViewBinder binder = new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { String name = cursor.getColumnName(columnIndex); if ("Colour".equals(name)) { int color = cursor.getInt(columnIndex); view.setBackgroundColor(color); return true; } return false; } } datasource.setViewBinder(binder);

更新 - 如果您使用自定义适配器(扩展 CursorAdaptor),那么代码不会有太大变化.您将覆盖 getView 和 bindView:

Update - if you're using a custom adapter (extending CursorAdaptor) then the code doesn't change a whole lot. You'd be overriding getView and bindView:

@Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView != null) { return convertView; } /* context is the outer activity or a context saved in the constructor */ return LayoutInflater.from(context).inflate(R.id.my_row); } @Override public void bindView(View view, Context context, Cursor cursor) { int color = cursor.getInt(cursor.getColumnIndex("Colour")); view.setBackgroundColor(color); String label = cursor.getString(cursor.getColumnIndex("GenreLabel")); TextView text = (TextView) findViewById(R.id.genre_label); text.setText(label); }

您的手动操作要多一些,但大致上是相同的想法.请注意,在所有这些示例中,您可以通过缓存列索引而不是通过字符串查找它们来节省性能.

You're doing a bit more manually, but it's more or less the same idea. Note that in all of these examples you might save on performance by caching the column indices instead of looking them up via strings.

更多推荐

Android,使用 SimpleCursorAdapter 设置颜色而不仅仅是字符串

本文发布于:2023-11-23 02:13:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619716.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不   仅仅是   字符串   颜色   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!