我将 SimpleCursorAdapter 与一个 xml 文件一起使用,其中定义了一些视图:
<LinearLayout ...>
<ImageView android:id="@+id/listIcon" />
<TextView android:id="@+id/listText" />
</LinearLayout>
我的目标是以编程方式设置 TextView 的文本颜色和 LinearLayout 的背景颜色(即 ListView 中的每一行);颜色是从数据库返回的。
例如,当我在没有抱怨的情况下发现它之后,我在尝试操纵 TextView 时遇到了 NPE:
TextView tv = (TextView) findViewById(R.id.listText);
tv.setTextColor(color); // NPE on this line
这是公平的;如果列表中有多个条目,则可以合理地假设“ R.id.listText ”将不起作用。所以我扩展了 SimpleCursor Adapter:
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
TextView text = (TextView) row.findViewById(R.id.listText);
// ImageView icon = (ImageView) row.findViewById(R.id.listIcon);
// If there's an icon defined
if (mIcon_id != 0) {
// icon.setImageResource(mIcon_id);
}
// If text color defined
if (mTextColor != 0) {
text.setTextColor(mTextColor);
}
// If background color set
if (mBackgroundColor != 0) {
row.setBackgroundColor(mBackgroundColor);
}
return(row);
}
我得到两个不同的错误:
- 在“ text.setTextColor(mTextColor) ”处引发了类似的 NPE
- 如果带有 ImageView 的行未注释,我会得到一个“ ClassCastException: android.widget.TextView ”,我正在调用“ row.findViewById(R.id.listIcon) ”
作为参考,我试图使用 Commonsware 的示例代码,并将其应用于我的情况。链接 (pdf)
改为:
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
if (convertView == null) convertView = View.inflate(mContext, R.layout.theme_item, null);
TextView text = (TextView) convertView.findViewById(R.id.listText_tv);
ImageView icon = (ImageView) convertView.findViewById(R.id.listIcon_iv);
// If there's an icon defined
if (mIcon_id != 0) {
icon.setImageResource(mIcon_id);
}
// If text color defined
if (mTextColor != 0) {
text.setTextColor(mTextColor);
}
// If background color set
if (mBackgroundColor != 0) {
convertView.setBackgroundColor(mBackgroundColor);
}
bindView(convertView, mContext, mCursor);
return(convertView);
}
现在我在下一个活动中得到一个 ClassCastException(单击列表项)。在下一个活动中没有任何修改;它在对具有条目的列表使用 SimpleListAdapter 时起作用(单击该列表会导致 Activity2),所以我认为在这个扩展类中我仍然做错了。