Android Studio ArrayAdapter无法运行程序崩溃

时间:2015-10-20 15:33:09

标签: android listview crash android-arrayadapter

我正在使用'ListView'和'ArrayAdapter'。我创建了一个名为listview_simple_layout.xml的新xml文件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:background="#ff0"
        android:textColor="#f00"
        android:textSize="30dp"
        android:textStyle="bold|italic"
        android:typeface="serif" />

</LinearLayout>

在onCreate方法中,当我将此xml文件传递给ArrayAdapter构造函数并运行该程序时,它崩溃了。请帮帮我... 这是我的onCreate函数:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Employee[] eList = new Employee[5];
        eList[0] = new Employee("Jagga", "Detroit Michigan", 1, 5000.0);
        eList[1] = new Employee("Bagga", "Alexandria Virginia", 2, 15000.0);
        eList[2] = new Employee("Haji", "San Diego California", 3, 25000.0);
        eList[3] = new Employee("Saqa", "Lahore Pakistan", 4, 35000.0);
        eList[4] = new Employee("Saqa", "Lahore Pakistan", 4, 35000.0);


        ListView lv = (ListView) findViewById(R.id.listView);

        ArrayAdapter<Employee> ad = new ArrayAdapter<Employee>(this,     R.layout.listview_simple_layout, eList);
        lv.setAdapter(ad);

    }

但每当我发表评论lv.setAdapter(ad)时,它都可以正常工作,但没有输出。

1 个答案:

答案 0 :(得分:0)

(这个问题已由我的导师解决了。这就是他所说的)

好的,正如我所料。如果仔细观察崩溃错误,它会说:

java.lang.IllegalStateException:ArrayAdapter要求资源ID为TextView

但是如果你看看你的布局文件,它是一个包裹在线性布局中的TextView。因此,数组适配器默认需要TextView,但它的布局比这更复杂。如果删除外部线性布局并在布局文件中保留单个TextView,则应该没问题(再次参见活动PDF并注意这一步骤是如何完成的)

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:background="#ff0"
    android:textColor="#f00"
    android:textSize="30dp"
    android:textStyle="bold|italic"
    android:typeface="serif" />

当然,我们可以指定非常复杂的布局,但是现在数组适配器只接受单个TextView。因此,对于更复杂的东西,我们必须手动覆盖数组适配器类。

相关问题