我正在使用“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)时,它都可以正常工作,但不显示任何输出。
最佳答案
(这个问题已经由我的老师解决了。他的意思是)
好的,正如我所料。如果仔细查看崩溃错误,它会显示:
java.lang.IllegalStateException:ArrayAdapter要求资源ID为TextView
但是,如果 checkout 布局文件,则它是包装在线性布局中的TextView。因此,数组适配器默认情况下期望使用TextView,但是它的布局比这更复杂。如果删除外部线性布局并仅在布局文件中保留一个TextView,则应该没问题(再次查看 Activity 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。因此,对于更复杂的内容,我们将不得不手动覆盖数组适配器类。
关于android - Android Studio ArrayAdapter不起作用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33240820/