开发者

OnClick ListView

开发者 https://www.devze.com 2023-01-27 20:07 出处:网络
I have followed this tutorial http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/

I have followed this tutorial http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/ and like to add an on click for the listview.

now here is my main.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="fill_parent" 
          android:orientation="vertical" >
<ListView
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:divider="@drawable/list_divider"
    android:dividerHeight="1px"
    android:cacheColorHint="#00000000"/>
</LinearLayout>

and here is my code:

setContentView(R.layout.main);    
steden = new ArrayList<voorDeLijst>();
this.m_adapter = new StedenAdapter(this, R.layout.list_item, steden);
setListAdapter(this.m_adapter);

List开发者_JS百科View lv = (ListView)findViewById(R.id.List);
lv.setOnItemSelectedListener(new OnItemSelectedListener() {
     public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
         AlertDialog.Builder adb = new AlertDialog.Builder(HelloAndroid.this);
         adb.setTitle("LVSelectedItemExample");
         adb.setMessage("Selected Item is = ");
         adb.setPositiveButton("Ok", null);
         adb.show();
    }

    public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub      
    }
});

The thing is that I am a beginner and with the code above I get an error because It cannot locate the listview. So I can't attach a OnItemClick Listener to it. but when I change <ListView android:id="@+id/android:list" to <ListView android:id="@+id/List" Then I can find the listview. but it gives an exception at the line: setContentView(R.layout.main);

So how do I attach an onClick/onItemClick to a Listview which has a custom adapter to bind objects to the listitems?


Found it, because my class extended the ListActivity I could do this:

@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{ 
    super.onListItemClick(l, v, position, id);
    // Get the item that was clicked
    Object o = this.getListAdapter().getItem(position);
    String keyword = o.toString();
    ...
}

I found it at http://www.anddev.org/viewtopic.php?t=22


Have you tried findViewById(android.R.id.list)? Really though, if your activity is basically one big list view, then you should be using a ListActivity for your activity, and that has an accessor that gives you direct access to the ListView.

0

精彩评论

暂无评论...
验证码 换一张
取 消