Fragment onListItemClick Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Fragment onListItemClick without wasting too much if your time.

The question is published on by Tutorial Guruji team.

My onListItemClick is never call when i click on item, the class is extends fragment not listfragment, because i have other view items in this fragment which is not list, so how to implement onlistitemclick in class extends fragment?

class

public class MainFiles extends Fragment 
{
    ArrayList<String> items;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
        View view = inflater.inflate(R.layout.files, container, false);

        Button button_up = (Button) view.findViewById(R.id.button_up);
        items = new ArrayList<String>();

        MyAdapter adapter = new MyAdapter(getActivity(), R.layout.row, items);
        ListView myList = (ListView) view.findViewById(R.id.list);
        myList.setAdapter(adapter);

        return view;
    }

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

    }
}

Answer

Explicitly add the OnItemClickListener to your ListView

myList.setOnItemClickListener(this);

You must also make sure that your Fragment implements the OnItemClickListener type:

public class MainFiles extends Fragment implements OnItemClickListener

Another way is to create a dedicated subclass of OnItemClickListener to pass to the ListView:

myList.setOnItemClickListener(new MyOnItemClickListener());

/* ... */

private class MyOnItemClickListener implements OnItemClickListener {

    /* ... */

}
We are here to answer your question about Fragment onListItemClick - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji