ata*_*ulm 4 android listactivity android-layout simplecursoradapter
我正在使用SimpleCursorAdapter和一个xml文件,其中定义了一些视图:
<LinearLayout ...>
<ImageView android:id="@+id/listIcon" />
<TextView android:id="@+id/listText" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
我的目的是以编程方式设置TextView的文本颜色和LinearLayout的背景颜色(即ListView中的每一行); 颜色从数据库返回.
我在尝试操作TextView时得到了NPE,例如,它发现它没有任何抱怨之后:
TextView tv = (TextView) findViewById(R.id.listText);
tv.setTextColor(color); // NPE on this line
Run Code Online (Sandbox Code Playgroud)
这是公平的; 如果列表中有多个条目,则可以合理地假设" R.id.listText "不起作用.所以我扩展了SimpleCursor适配器:
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);
}
Run Code Online (Sandbox Code Playgroud)
我得到两个不同的错误:
作为参考,我试图使用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);
}
Run Code Online (Sandbox Code Playgroud)
现在我在下一个活动中得到一个ClassCastException(在列表项上单击).在下一个活动中没有修改任何内容; 当使用SimpleListAdapter作为具有条目的列表(点击将导致Activity2)时,它工作,所以我认为这仍然是我在这个扩展类中做错了.
这是不正确的convertView永远是现有的实例; 你应该检查它是否为null然后实例化它.如果没有,您可以像改变它一样进行更改.
这应该是这样的:
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = //inflate your row here
View row = convertView;
//Manipulate the row here
return(row);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1982 次 |
| 最近记录: |