列表适配器错误
有人可以告诉我这段代码有什么问题吗?
它应该是来自 XML 文件的 ListView,然后在 Java 中引用该文件。 唉,每次进入 Menu 类时它都会使我的应用程序崩溃。
public class Menu extends ListActivity {
String Name_for_classes[] = {"- 1-9 Tabels -", "- 10-19 Tabels -", "- 20-29 Tabels -" };
String Tabel_classes[] = {"First", "Second", "Third"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.menu, Name_for_classes));
ListView list = getListView();
list.setTextFilterEnabled(true);
}
}
Could someone tell me what is wrong with this piece of code?
It is supposed to be a ListView from an XML file that is then referred to in Java.
Alas, it crashes my application every time it enters the Menu class.
public class Menu extends ListActivity {
String Name_for_classes[] = {"- 1-9 Tabels -", "- 10-19 Tabels -", "- 20-29 Tabels -" };
String Tabel_classes[] = {"First", "Second", "Third"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.menu, Name_for_classes));
ListView list = getListView();
list.setTextFilterEnabled(true);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的,我们假设您的 ListView 位于名为 my_listview.xml 的 XML 文件中。
Okay, let's assume you have your ListView in an XML file called my_listview.xml.
我不确定 R.layout.menu 中的内容,但通过命名其活动布局来猜测。这应该与 onCreate 中的 setContentView(R.layout.menu) 一起使用。传递到 ArrayAdapter 的布局是用于填充列表视图的 TextView。
I'm not sure what is in R.layout.menu, but guessing by the naming its the activity layout. This should be used with setContentView(R.layout.menu) in onCreate. The layout that is passed into the ArrayAdapter is the TextView you are using to populate the listview.
您忘记在 onCreate 方法中调用 setContentView,因此您的 listview 尚未被引用。
当您使用 setContentView 时,相当于说“对于此活动,我想使用模板 'myTemplate.xml'”
之后,您必须将 java ListView 属性“链接”到模板中声明的列表视图。
You have forgotten to call the setContentView in your onCreate method, so your listview is not referenced yet.
When you use setContentView, it is equivalent as sayin 'for this activity I want to use the template 'myTemplate.xml'
After that, you have to 'linked' your java ListView attribute to the listview declared in your template.