Reputation: 29287
i want to create a custom list view, but when i run the program it breaks with a exception:
logcat:
in onCreate method:
ListView list = (ListView) findViewById(android.R.id.list);
String items[] = {"cat", "dog", "horse", "monkey"};
list.setAdapter(new myAdapter(items));
in myAdapter class:
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;
}
}
My main activity:
<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>
And my template row:
<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>
How can i fix this problem? Thanks
Upvotes: 0
Views: 94
Reputation: 22493
inflate like this
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.row, null);
Upvotes: 0
Reputation: 10395
Inflate your view like :
View view = inflater.inflate(R.layout.row, parent,false);
AttachToRoot (Third Argument): Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML
Upvotes: 1
Reputation: 111
You forgot to set the third parameter (attachToRoot) to false while inflating the row.
Try this:
View view = inflater.inflate(R.layout.row, parent, false);
It would be even better to re-use the convertView if available:
View view = convertView;
if (convertView == null) {
view = inflater.inflate(R.layout.row, parent, false);
}
Upvotes: 3