我用Eclipse编写了关于Android中ListView的代码。我已经按照书上的教程。但是在我复制代码并使用Emulator运行之后。出现强制关闭消息。如下图所示:
我不知道发生了什么问题。相反,我在这个问题中搜索了解决方案: Can't create android onListItemClick method
我的代码如下图所示:
下图显示了logcat:
你能给我解决方案吗?
答案 0 :(得分:2)
确保您的ListView名为<ListView android:id="@android:id/list"
。
由于您使用的是ListActivity
(同样适用于ListFragments
),因此这是 ListView的唯一可能名称。
答案 1 :(得分:0)
试试这个,
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"
android:orientation="vertical" >
<TextView
android:id="@+id/output"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#758AA7"
android:padding="1px"
android:text="Click : "
android:textColor="#ffffff" />
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
MainActivity.java
公共类MainActivity扩展了ListActivity {
TextView content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
content = (TextView) findViewById(R.id.output);
String[] CoffeeShop = {"Creation","Starbucks","Caribou","Mo'Joe" };
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, CoffeeShop);
// Assign adapter to List
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) l.getItemAtPosition(position);
content.setText("Click : \n Position :" + itemPosition
+ " \n ListItem : " + itemValue);
}
}