How to Override LongPress in ListFragment?

Deadly 提交于 2019-12-21 04:53:11

问题


I have a ListFragment Activity.

I want to create a method for onItemClickedLongPress, so that when the user does this. a menu pops up. I am familiar with creating the menu.

So if some one would please, give me further instructions on how to set Override the longpress in a ListFragment activity?


回答1:


edit: this sample shows how to show something other then system menu fx. QuickAction from https://github.com/lorensiuswlt/NewQuickAction

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //.......
    registerForContextMenu(getListView());
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    AdapterView.AdapterContextMenuInfo amenuInfo = (AdapterView.AdapterContextMenuInfo) menuInfo;
    Object item = getListAdapter().getItem(amenuInfo.position);
    //item could be Cursor/String/YourObject it depends on Adapter
    //show popup fx. QuickAction from https://github.com/lorensiuswlt/NewQuickAction
    QuickAction qa = new QuickAction(getActivity());
    qa.setAnimStyle(QuickAction.ANIM_AUTO);
    qa.show(amenuInfo.targetView);
}

EDIT: This ansewer is not good ... why i did this such strange method? because eclipse intellisense did not propmt "good" setOnLongClickListener for ListView (since ListView has at least 2 setOnLongClickListener methods ... one from View and second from AdapterView class) ... the easiest way is let your ListFragment implement AdapterView.OnItemLongClickListener and then in onViewCreated add code getListView().setOnLongClickListener(this);




回答2:


By "long press", I think you are referring to the context menu. For a ListFragment, all you should have to do is to register for the context menu:

@Override
public void onActivityCreated(Bundle icicle) {    
    registerForContextMenu(getListView());
}

Once you do that, the ListFragment should call onCreateContextMenu() and onContextItemSelected() when it detects a long press.




回答3:


Modified Erich Douglass' answer further.. for some reason my own app would crash until I modified my code and placed the registration into onViewCreated as follows:

@Override
public void onViewCreated (View view, Bundle savedInstanceState) {
    registerForContextMenu(getListView());
}



回答4:


getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        // Show your popout menu here.
    }
});


来源:https://stackoverflow.com/questions/7419012/how-to-override-longpress-in-listfragment

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