我想创建一个自定义列表视图,但是当我运行该程序时,它会出现异常:
logcat的:
:
ListView list = (ListView) findViewById(android.R.id.list);
String items[] = {"cat", "dog", "horse", "monkey"};
list.setAdapter(new myAdapter(items));
myAdapter 类中的
private class myAdapter extends ArrayAdapter<String>{
private String items[];
public myAdapter(String items[]) {
super(ListViewExample.this, R.layout.row, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.row, parent);
TextView label=(TextView)view.findViewById(R.id.row_textView1);
label.setText(items[position]);
return view;
}
}
我的主要活动:
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
我的模板行:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/row_textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
我该如何解决这个问题?感谢
答案 0 :(得分:3)
在向行充气时,您忘记将第三个参数(attachToRoot)设置为false。
试试这个:
View view = inflater.inflate(R.layout.row, parent, false);
如果可用的话,重新使用convertView会更好:
View view = convertView;
if (convertView == null) {
view = inflater.inflate(R.layout.row, parent, false);
}
答案 1 :(得分:1)
夸大你的观点,如:
View view = inflater.inflate(R.layout.row, parent,false);
AttachToRoot (第三个参数):是否应将膨胀的层次结构附加到根参数?如果为false,则root仅用于为XML中的根视图创建LayoutParams的正确子类
答案 2 :(得分:0)
像这样膨胀
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.row, null);