Android: onListItemClick in Activity

2019-02-02 02:25发布

Previous time I asked a question here I learned a lot so I guess it's worth a shot to try it again.

I am using the lazy list by Fedor from this link: Lazy load of images in ListView

It's working like a charm. BUT, Fedor is making his main class extend Activity instead of ListActivity. Because of this, I am no longer able to use a listItemClick listener. Eclipse declares some errors around onListItemClick(). It works when I turn

    @Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
     // Intent launcher here
}

into

   protected void onListItemClick(ListView l, View v, int position, long id) {
     // Intent launcher here
   }

But the intent launcher doesn't work. Neither does a toast notification.

When I turn the Activity in a ListActivity, Eclipse doesn't stagger, but my emulator gives me a force close.

How do I get

  • Either onListItemClick() click in the activity (preferable)
  • Or do I transform the code into a ListActivity without force close?

Thanks a lot in advance.

8条回答
倾城 Initia
2楼-- · 2019-02-02 03:20

For a non-ListActivity to have an item-clicked-listener for a ListView, you have to call the setOnItemClickedListener() on the ListView (you may need to get that using findViewById() if it's coming from XML)

Rather than just overriding ListActivity's onListItemClickListener(), here you'd have your invoking Activity implement AdapterView.onItemClickedListener() and pass it as the parameter to setOnItemClickedListener().

(If you read the source code for ListActivity (which I recommend), you'll see it just does exactly that behind the scenes by creating an internal listener object that calls your overridden onListItemClick()).

查看更多
劫难
3楼-- · 2019-02-02 03:22

I am writing my answer as:

1) the code by @Falmarri needs some update
2) My suggested edit was totally rejected XD
3) Stackoverflow is not allowing me to write a comment.

Here is the code:

ListView listView = (ListView) findViewById(R.id.my_listview_in_layout);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        //Do stuff
        //...
    }
});


Reference: According to android.widget.AdapterView.OnItemClickListener , public method onItemClick() is the method invoked when an item is clicked {instead of unknown protected method onListItemClick() }

查看更多
登录 后发表回答