Long click on ListFragment

旧城冷巷雨未停 提交于 2019-12-03 10:32:28

问题


I'm working with a ListFragment and doing a onListItemClick. Everything works fine, but now I want to use a long Item Click (e.g setOnItemLongClickListener(new OnItemLongClickListener() for an Activity). How can I use this in my fragment?

Thanks!


回答1:


Yes, the solution posted by tsync works for me. I too had ran into same problem and considered that this is not possible. I tried the above suggestion as follows:

public  class ProjectsFragment extends ListFragment {

@Override
public void onActivityCreated(Bundle savedState) {
    super.onActivityCreated(savedState);

    getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            Toast.makeText(getActivity(), "On long click listener", Toast.LENGTH_LONG).show();
            return true;
        }
    });

and it worked!




回答2:


Depending on what you want to realize you can use the given methods for context menues:

First register the View class which gets long pressed (inside your Fragment class):

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    registerForContextMenu(this.getListView());
}

Than implement these two methods, to create a context menu and do what ever you want when a menu item is clicked:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    MenuInflater inflater = this.getActivity().getMenuInflater();
    inflater.inflate(R.menu.my_context_menu, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item) {

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {

        case R.id.add: // <-- your custom menu item id here
            // do something here
            return true;

        default:
            return super.onContextItemSelected(item);
    }
}



回答3:


This works for me

getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
    public boolean onItemLongClick(AdapterView<?> av, View v, int position, long id) {
        //Get your item here with the position                   
        return true;
    }
});


来源:https://stackoverflow.com/questions/6732611/long-click-on-listfragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!