14

EDIT: SOLVED. If there's anything focusable in the XML of the items, it will break the touch of the list, in other words, android:focusable=false to all the checkboxes, switches or anything like that of ur list. And done =)

Ok so, here's my problem.

I wrote a app that uses tabs and fragments, and it all goes the way I want except for the thing that when I try to capture a onItemClick on a listView it does not even mark the row as touched/pressed/selected.

I've been reading a little bit about and many people have the same issue, but I did not found any responses that helped me at all.

I don't want to implement a ListFragment, in fact I don't even know how/why I should, and since all my code is already working, I don't know if implementing one will give me much more work to do, so, here it is:

Is it possible to implement a listener for a click on a listView, inside a fragment? and if it is, HOW?

PD: minSDK=14, tatgetSDK=15

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
Dunnow
  • 414
  • 1
  • 5
  • 22
  • 2
    Usually, you use `OnItemClickListener`, not `OnClickListener`, with a `ListView`, regardless of whether or not it is in a fragment. – CommonsWare Feb 15 '13 at 17:18
  • ... i know that... i was, obviously, refering to onItemClickListener method, and it does not work inside a fragment. – Dunnow Feb 16 '13 at 17:38
  • @Dunnow I have a similar problem. Can you help me solve it? Its posted here. http://stackoverflow.com/questions/42542056/android-async-task-json-parsing-onitemclicklistener-not-working – Sulav Timsina Mar 02 '17 at 19:49

7 Answers7

9

Just put

android:focusable="false"
android:clickable="false"

in layout. For all textviews,buttons etc.

Ashwin S Ashok
  • 3,623
  • 2
  • 29
  • 36
5

Here's a code snippet that'll do what you want.

ListView lv;

//code to get the listView instance using findViewByID etc

lv.setOnItemClickListener(new OnItemClickListener()
{
    @Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
    { 
        Toast.makeText(EnclosingActivity.this, "Stop Clicking me", Toast.LENGTH_SHORT).show();
    }
});

People usually trip on this, see if you have got this covered:

All clicks and call backs (eg: the menu/actionbar callbacks) are sent to the activity the fragment is bound to, so they must be in the activity class and not the fragment class.

Dheeraj Bhaskar
  • 18,633
  • 9
  • 63
  • 66
  • tried that... not working inside a fragment, as I already stated – Dunnow Feb 16 '13 at 17:39
  • it gives me an error if i execute this code inside the "onCreate" method, launches the debug before my activity even starts :S And if I set this snippet on the main itself, it marks the declaration and the lv=(ListView) get... as a wrong line. – Dunnow Feb 18 '13 at 20:54
  • @Dunnow can you add it as an answer or accept one of the answers here – Dheeraj Bhaskar Feb 20 '13 at 20:04
  • i've edited the first post to reflec how i solved it, but i'll mark yours as answer i guess since it's still correcto to do it with that code, problem wasn't there, but in the XML u_u – Dunnow Feb 21 '13 at 21:02
  • 2
    @Dunnow, if you put this code into your "onViewCreated" code inside your fragment class (a class that extends Fragment), it will work just fine as long as you initialize your ListView (lv = (ListView)view.findViewById(R.id.YOURlv);) – whyoz May 13 '13 at 23:05
  • @DheerajBhaskar I have a similar problem. Can you help me solve it? Its posted here. http://stackoverflow.com/questions/42542056/android-async-task-json-parsing-onitemclicklistener-not-working – Sulav Timsina Mar 02 '17 at 19:49
  • @SulavTimsina let me take a look – Dheeraj Bhaskar Mar 03 '17 at 05:15
5

This may be helpful Answer by raghunanadan in below link solved my problem

listview OnItemClick listner not work in fragment

Add this to the layout

android:descendantFocusability="blocksDescendants"

Community
  • 1
  • 1
Vinay
  • 1,284
  • 14
  • 24
  • Your answer got into `Low quality review queue` as a `link-only answer`. You cannot see the queue as of now due to low reputation in SO, but others, with higher reputation, can. When this kind of answers is being reviewed by others, someone can leave a comment letting you know the question may need an improvement (like me in this case) or down vote (like the guy that down voted). So please, try avoiding link-only answer. – Onik Oct 09 '15 at 13:48
2

Two awesome solutions were this, if your extending ListFragment from a fragment, know that mListView.setOnItemClickListener wont be called before your activity is created, As @dheeraj-bhaskar implied. This solution ensured it is set when activity has been created

@Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long rowId) {
                // Do the onItemClick action

                Log.d("ROWSELECT", "" + rowId);
            }
        });
    }

While looking at the source code for ListFragment, I came across this

    public class ListFragment extends Fragment {
        ...........................................
     ................................................

        final private AdapterView.OnItemClickListener mOnClickListener
                = new AdapterView.OnItemClickListener() 
{
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
{
                onListItemClick((ListView)parent, v, position, id);
            }
        };
       .................................................................
    ........................................................................

    public void onListItemClick(ListView l, View v, int position, long id) 
{
        }
}

An onItemClickListener object is attached and it calls onListItemClick() As such the other similar solution, which works in the exact same way is to override onListItemClick()

 @Override
        public void onListItemClick(ListView l, View v, int position, long rowId) {
            super.onListItemClick(l, v, position, id);
           // Do the onItemClick action

                    Log.d("ROWSELECT", "" + rowId);
        } 
Otieno Rowland
  • 2,182
  • 1
  • 26
  • 34
0

Here is an overview of the workflow, create your ListView and it's corresponding Adapter(used to map your underlying data to the items in the ListView), set the adapter to the ListView, and then add an OnItemClickListener to it.

More details and sample code can be found at: http://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViews

Brent Hronik
  • 2,357
  • 1
  • 27
  • 43
  • The only thing that would be different in the fragment would have to call `getActivity()` everywhere a context is required. – Brent Hronik Feb 16 '13 at 17:38
  • final Activity activity = getActivity(); Toast.makeText(activity, "Faena seleccionada: " + " " + fullObject.getTitle(), Toast.LENGTH_LONG).show(); – Dunnow Feb 16 '13 at 17:56
  • the items on the list aren't even marked as blue when i touch them, so, NOTHING of the list is working, i populated it, i set my adapter, i can even check uncheck the checkboxes i added to them, but i can't do a "onItemClick" – Dunnow Feb 16 '13 at 17:57
  • Would you mind posting your entire list view, adapter and on itemClickListener initialization, as well as your xml for your fragment? – Brent Hronik Feb 16 '13 at 18:02
  • http://ideone.com/P715aq <-- fragment http://ideone.com/xFMj39 <-- custom adapter http://ideone.com/we97d1 <-- results of the adapter (hardcoded, once i get it working will clean code and shit) i think this is all list/fragment related (the fragment is part of a tabbed interface) – Dunnow Feb 16 '13 at 18:08
  • Hmm I am really at a loss for words, all appears to be correct :/ – Brent Hronik Feb 16 '13 at 22:31
  • Ahh, should have asked to look at the layout of the list item. Good catch though! – Brent Hronik Feb 19 '13 at 16:30
  • In fact u did, the thing was that i didn't even posted it as i thought it didn't even matter (never had a "focusable item" on a list before so... i just assumed it was correct as well) – Dunnow Feb 19 '13 at 19:09
0

If you want to pass data from fragment to any activity on Listview click then you can modify your code like...

class HistoryFragment extends Fragment {  ListView historyListView;
public HistoryFragment() {
    // Required empty public constructor
}

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

    View v= inflater.inflate(R.layout.fragment_history, container, false);
    historyListView= (ListView) v.findViewById(R.id.historyDataListView);

    sendRequest();  //it is my meathod to load the listview and set the adapter
    return  v;
}

public void onStart() {
    super.onStart();
    historyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            Intent intent=new Intent(getActivity(), DisplayDetails.class);

            intent.putExtra("text", historyListView.getItemAtPosition((int) l).toString());
            startActivity(intent);
          //  Toast.makeText(getActivity(),"Hello.. "+historyListView.getItemAtPosition((int) l).toString(),Toast.LENGTH_LONG).show();
        }
    });
}}
Javed
  • 1,613
  • 17
  • 16
-1

the button will affect the listener, try avoid using button and re compile, it should work