我已經使用Eclipse編寫了有關Android中ListView的代碼。我已經遵循了基於書本的教程。但是,我複製代碼並運行模擬器後。出現強制關閉消息。像下面的圖片:列表視圖無法運行
我不知道什麼的probem發生。相反,我在尋找這個問題的解決方案: Can't create android onListItemClick method
而且我的代碼像下面的圖片:
圖像下面所示的logcat的: 你能不能給我的解決方案?
我已經使用Eclipse編寫了有關Android中ListView的代碼。我已經遵循了基於書本的教程。但是,我複製代碼並運行模擬器後。出現強制關閉消息。像下面的圖片:列表視圖無法運行
我不知道什麼的probem發生。相反,我在尋找這個問題的解決方案: Can't create android onListItemClick method
而且我的代碼像下面的圖片:
圖像下面所示的logcat的: 你能不能給我的解決方案?
試試這個,
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);
}
}
請解釋爲什麼爲了更好的理解,OP只學習與解釋.... – Opiatefuchs
請檢查我已更新answer.it的工作完美。 –
感謝您的回答,我的錯誤在初始化ListView的.xml文件中。基於@Der Golem在這個問題的評論中說 – Ilham
確保您的ListView名爲<ListView android:id="@android:id/list"
。
由於您使用的是ListActivity
(這同樣適用ListFragments
),這是爲您的ListView唯一可能的名稱。
你的logcat在哪裏?發佈它。 '它在這裏扮演着非常重要的角色.' –
發佈您的logcat –
您確定TextView和ListView位於'R.layout.main'文件內嗎? –