Android: onListItemClick in Activity
Asked Answered
S

8

11

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.

Sanguinolent answered 2/11, 2010 at 17:4 Comment(0)
R
1

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() }

Reproachless answered 14/2, 2017 at 8:11 Comment(0)
S
30

A listItemClickListener is attached to a ListView. When you changed ListActivity to Activity, your class no longer has a view associated with it and thus an Activity class has no idea what to do with an onListItemClickListener.

You just have to attached a listener to your ListView:

listview.setOnItemClickListener(new OnItemClickListener(){
    @Override
    protected void onListItemClick(AdapterView<?> parent, View view, int position, long id){
        //Do stuff
    }
});
Sidestroke answered 2/11, 2010 at 17:10 Comment(1)
Man!! I am about a year and half late to the lazy load party and you are still a life saver.... :-)Strainer
B
1

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()).

Brindabrindell answered 2/11, 2010 at 17:10 Comment(0)
S
1

I have been working on this all day and after making my own ArrayAdapter I couldn't figure out how to change classes in my list.

Here's how I found out how to do it. After I called my array i simply finished out my code in that method by doing.

ListView lv =getListView();
lv.setOnItemClickListener(this);

Then after all my text i put

public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {
    String item = (String) getListAdapter().getItem(position);

    if (item.equals("Economy"))
    {
        Intent intent = new Intent(packages.this, economy.class);
        startActivity(intent);
    }
    else if (item.equals("Basic"))
    {
        Intent intent = new Intent(packages.this, basic.class);
        startActivity(intent);
    }
    else if (item.equals("Professional"))
    {
        Intent intent = new Intent(packages.this, professional.class);
        startActivity(intent);
    }
    else if (item.equals("Custom Applications"))
    {
        Intent intent = new Intent(packages.this, applications.class);
        startActivity(intent);
    }
}

Between I managed to completely customize my ListView with custom font and backgrounds. I'm sure a ton of you don't really care. But I'm exited and was hoping by posting this that I might help someone in the future.

Subalpine answered 17/4, 2012 at 3:45 Comment(0)
R
1

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() }

Reproachless answered 14/2, 2017 at 8:11 Comment(0)
H
0

If you are using ListActivity then you want to do something like this:

public class YourClass extends ListActivity implements OnItemClickListener{

    @Override
    public void onCreate(Bundle icicle){
        super.onCreate(icicle);
        setContentView(R.layout.your_layout);

        getListView().setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // your stuff here
    }
}

This is not the only way to set an OnItemClickListener. Look other answers. This is the way I like to do it since it's clearer and easier to read.

Holiday answered 2/11, 2010 at 17:11 Comment(7)
This did it.. Thanks so much! This apparently also works on regular Activities.Sanguinolent
What is this? Dear god don't do this. If you're extending listActivity you don't need to listen for onItemClickListener. And if you're extending Activity, OnItemClickListener doesn't apply to all Activities so you shouldn't implement that to the activity.Sidestroke
I don't exactly follow. Why would it need to apply to all activities? I just have a single list that I want to apply it to.Sanguinolent
@Sidestroke I don't get what you mean. "And if you're extending Activity, OnItemClickListener doesn't apply to all Activities so you shouldn't implement that to the activity" of course, it does not apply to all activities, and that's just as we expect it to be.Holiday
I'm talking about OO principles in general. OnItemCLickListener doesn't apply to an activity. You should apply the onItemClickListener to what it applies to, the listview.Sidestroke
Ahh... I get it... in that case creating an anonymous inner class (as you do in you answer (and as I always do when the event fired is simple)) is also not good. The better way, following OO principles, is creating a separate class to handle the event. You know, there are tons of principles that points to that direction (say "separate things that change, from those that do not" or "Strive for loosely coupled design between objects that interact", etc.), and that's even the base of the MVC.Holiday
Yeah creating a separate class is totally fine. Just break out the anonymous inner class to a class-method class. It's just poor design to have your activity implementing 11 different interfaces if those interfaces really only apply to elements of that class, not the class itself.Sidestroke
P
0

I have simply added following in onCreate():

    listvview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            setPaymentDetails();
        }
    });

Outside of onCreate() added setPaymentDetails():

protected void setPaymentDetails()
{
    Intent intent = new Intent(this, SetPaymentDetailsActivity.class);
    startActivity(intent);
}
Progression answered 15/2, 2013 at 2:43 Comment(0)
L
0

FE.java

package com.example.rfe;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class FE extends ListActivity {
 public List<String> d = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.file);
        d = new ArrayList<String>();    
        Scanner in = null;
        File f = new File("/sdcard/input.txt");
        try
        {
        in = new Scanner(new FileReader(f));
        while(in.hasNext()==true)
        {
            d.add(in.nextLine());   
        }
        }catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
        ArrayAdapter<String> fileList =
                  new ArrayAdapter<String>(this, R.layout.row, d);
                 setListAdapter(fileList);
    }
 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) 
 {
     String selection = l.getItemAtPosition(position).toString();
     Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
    super.onListItemClick(l, v, position, id);
}
}
Lumbago answered 21/3, 2013 at 15:27 Comment(1)
This piece of code works i had a tough time figuring it out,it might help someone.You need 2 XML files file and row.Lumbago
M
0

Assume you have datasource Fruit contain few strings. You can define the onCreate() as following:

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_fruit,
                FRUITS)); // context is this, style is list_fruit, Context, ,data_binding to FRUITs

And then write the onListItemClick() as following:

protected void onListItemClick(ListView parent, View v, int position, long id) {
                Toast.makeText(this,  " You selected  " + FRUITS[position], Toast.LENGTH_SHORT).show();
        }

I hope it works for you :)

Maliamalice answered 31/5, 2013 at 14:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.