0

我想创建一个自定义列表视图,但是当我运行程序时它会因异常而中断:

日志猫:
日志猫屏幕

onCreate方法中:

    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>

我该如何解决这个问题?谢谢

4

3 回答 3

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);
}
于 2013-10-09T09:36:01.503 回答
1

夸大你的观点,如:

View view = inflater.inflate(R.layout.row, parent,false);

AttachToRoot(第三个参数):膨胀的层次结构是否应该附加到根参数?如果为 false,则 root 仅用于为 XML 中的根视图创建正确的 LayoutParams 子类

于 2013-10-09T09:36:41.090 回答
0

像这样膨胀

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.row, null);
于 2013-10-09T09:40:55.523 回答