我有一个包含多个 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/