android - 如何以编程方式更改 ListView 内 TextView 的背景颜色?

标签 android colors android-listview background-color textview

我有一个包含多个 TextView 项目的 ListView。该列表是在运行时创建的,并且大小可能会有所不同。我想根据运行时生成的浮点值设置 TextView 项目的背景。我正在使用 ArrayAdapter。

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_fruit,ratios));  
final ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setBackgroundColor(Color.LTGRAY);
((TextView) listView.getChildAt(0)).setBackgroundColor(Color.CYAN);

最后一行抛出 NullPointerException。由于某种原因,我无法访问 listView 中的这个 TextView。如果我直到运行时才知道颜色,我该如何动态设置 TextView 的背景颜色?

最佳答案

只需找到 TextView 即可:

TextView myTextView = (TextView)findViewById(R.id.yourTextViewId);

做你想做的事,例如:

myTextView.setTextColor(color); 
myTextView.setBackgroundColor(color);

编辑:

请在这个网站上找到如何实现“android自定义适配器”?

关于android - 如何以编程方式更改 ListView 内 TextView 的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11771280/

相关文章:

android - 错误 "Could not create task ' :app:injectCrashlyticsMappingFileIdFlavorXDebug"after upgrading from Fabric to Firebase

Java 如何识别照片颜色?

android - 在 ArrayAdapter 中设置 ArrayList<HashMap<String,String>>

android - 控制 ListActivity 中的各个 View

android - 如何将多个触摸操作附加到单个列表项?

android - com.fasterxml.jackson.databind.exc.MismatchedInputException : Unexpected token (START_OBJECT), 预期 START_ARRAY:

安卓显示刷新率

使用 digicert 在服务器中更新证书后出现 Android ssl 证书错误

emacs - 更改 Emacs 语法突出显示颜色

java - 返回数组元素的长度