Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListFragment onItemClickListener not working

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!

like image 691
dthomasen Avatar asked Dec 29 '12 09:12

dthomasen


2 Answers

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);
    }
like image 174
Lalit Poptani Avatar answered Oct 21 '22 11:10

Lalit Poptani


It is due to custom list item. The default focus is with custom list item (button/textview). It causes this issue.

Please add android:descendantFocusability="blocksDescendants" in root layout of list element. Hope this will help someone.

like image 35
Nandha Avatar answered Oct 21 '22 11:10

Nandha