【发布时间】:2013-12-03 04:49:02
【问题描述】:
我正在尝试使用来自 tutorial 的 LazyAdapter 类填充自定义 ListView
我想用自定义设计制作列表视图项目。布局文件list_row.xml 在我的布局文件中,就像在教程中一样。这是LazyAdapter类中稍作修改的getView函数:
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
//vi = inflater.inflate(R.layout.list_row, null); //EDITED
vi = inflater.inflate(R.layout.list_row, parent, false);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView subtitle = (TextView)vi.findViewById(R.id.subtitle); // artist name
//ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image);
//This is not needed
//HashMap<String, String> post = new HashMap<String, String>();
HashMap<String, String> post;
post = data.get(position);
// Setting all values in listview
title.setText(post.get("title")); //the code crashes here
subtitle.setText(post.get("subtitle"));
//imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
return vi;
}
这段代码在title.setText() 崩溃,因为标题为空。我在某处读到这是有道理的,因为这个 LazyAdapter 在 setContentView 之前调用了 findViewById 或其他东西..
那么我该怎么做呢?这段代码对那个人有什么作用?
更新
这是list_row.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<!-- Title -->
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#040404"
android:typeface="sans"
android:textSize="14sp"
android:textStyle="bold"/>
<!-- Subtitle -->
<TextView
android:id="@+id/subtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/subtitle"
android:textColor="#343434"
android:textSize="10sp"
android:layout_marginTop="1dip" />
</RelativeLayout>
为了节省空间,我只从主活动布局文件中添加ListView xml:
<ListView
android:id="@+id/feedListView"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/volumeControl1">
</ListView>
适配器代码:http://pastebin.com/niC1yXiJ
还有堆栈跟踪:http://pastebin.com/myW8B0Xz
【问题讨论】:
-
setContentView 由活动使用,在这种情况下不使用。如果 inflater 真的用您引用的 id 对布局进行充气,则不应有空指针。你能发布随之而来的xml吗?此外,您应该调用 inflater.inflate(R.layout.list_row, parent, false);这允许膨胀的布局使用父布局,但 false 阻止它被附加。您也可以发布错误日志
-
hashmap 代码行下面的数据是什么?如果您在标题处得到空值,则在 post hashmap 中没有键标题的值。
-
HashMap 数据被填充.. 工作正常..
-
也发布堆栈跟踪。
-
忽略 Sathish 的评论,这不是鸭式语言。最好使用 String.format("%1$s", post.get("title"))
标签: android nullpointerexception android-lazyadapter