问题
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)
{
}
}
回答1:
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 {
/* ... */
}
回答2:
You forget to set the setOnItemClickListener
after myList.setAdapter(adapter);
add this:
myList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position,long id){
new File(items.get(position));
fileList(path.get(position));
showPath(current_path);
}
});
回答3:
I have implement listener in fragment like this
public class DetailsFragment extends Fragment implements OnItemClickListener {
private ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_details, container, false);
// list view
listView = (ListView) root.findViewById(R.id.listView);
listView.setListAdapter(new DetailsAdapter(getActivity(), list));
listView.setOnItemClickListener(this);
return root;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// handle click here
}
}
回答4:
Your fragment has to extend ListFragment, you can have more things in your layout other than a list if your layout has a listview with id=android:id/list
来源:https://stackoverflow.com/questions/13811023/fragment-onlistitemclick