ListFragment onItemClickListener not working

dthomasen picture dthomasen · Dec 29, 2012 · Viewed 9.5k times · Source

I'm using the tabbed layout (with swipe). Here I have 3 tabs with controlled by a SectionsPagerAdapter. Each tab is a ListFragment.

Now I want to get an event fired when one of the items in the list is clicked. I would like a listener for each tab.

Here's the code now (Which isn't working, event is not fired).

public class NyhederFragment extends ListFragment {
     public static final String ARG_SECTION_NUMBER = "section_number";
     private static final String TAG="NyhederFragment";
     private List<Item> newsItems;
     private ArrayList newsHeadlines;
     private ArrayAdapter adapter;
     private BroadcastReceiver updateReciever;

public NyhederFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    ListView newsList = new ListView(getActivity());
    newsList.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    newsList.setId(R.id.list);
    DatabaseHelper dbConn = new DatabaseHelper(getActivity());

    newsItems = dbConn.getAllItemsFromNews();
    newsHeadlines = new ArrayList();
    for(Item i : newsItems){
        newsHeadlines.add(i.getTitle());
    }

    adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, newsHeadlines);

    setListAdapter(adapter);

    newsList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                  int position, long id) {
            Log.i("debug", "single click");
        }
    });

    dbConn.close();

    getActivity().registerReceiver(updateReciever, new IntentFilter("ArticlesUpdated"));
    return newsList;
}
}

What is it, I'm doing wrong?

Thanks a lot in advance!

Answer

Lalit Poptani picture Lalit Poptani · Dec 29, 2012

If you are using ListFragment then you can simply use its override method onListItemClick()

@Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
    }