如何在List活动中实现onItemClickListener

din*_*707 2 android android-layout

以下是我的ListActivity,onCreate代码

public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            fakeTripBuilder();

            setContentView(R.layout.cutom_list_view);

            SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.custom_row_view, 
                    new String[] {"stop","distance","time","icon","mode"},
                    new int[] {R.id.text_stop,R.id.text_distance, R.id.text_time, R.id.icon, R.id.text_mode});

            populateList();
            setListAdapter(adapter);
}
Run Code Online (Sandbox Code Playgroud)

在同一个类里面,我有以下方法

 @Override
       protected void onListItemClick(ListView l, View v, int position, long id){
           super.onListItemClick(l, v, position, id);
           Log.d("Travel","You choosed!");
           Object o = this.getListAdapter().getItem(position);
           Toast.makeText(this, "You Choosed"+o.toString(), Toast.LENGTH_LONG).show();
       }
Run Code Online (Sandbox Code Playgroud)

这是"custom_list_view.xml"

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clickable="false"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical" >
<ListView 
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000fff"
    android:layout_weight="2"
    android:drawSelectorOnTop="false">
</ListView>
<TextView 
    android:id="@id/android:empty"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#FFff00"
    android:text="No data"
/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

问题是,当我点击它时,onListItemClick方法不会调用.救命 !!

Dav*_*ott 6

要在ListActivity中获取对ListView的引用,您应该调用:

ListView lv = getListView();
Run Code Online (Sandbox Code Playgroud)

您不需要设置单击侦听器,它已经有一个.简单地覆盖:

 @Override
 public void onListItemClick(ListView l, View v, int position, long id) {
     Object item = lv.getAdapter().getItem(position);

 }
Run Code Online (Sandbox Code Playgroud)

在你的xml文件中,ListView应该有id:

android:id="@android:id/list" 
Run Code Online (Sandbox Code Playgroud)

编辑

你需要删除

android:clickable="false"
Run Code Online (Sandbox Code Playgroud)

从布局中允许单击任何子视图