如何覆盖ListFragment中的长按事件?

6

我有一个ListFragment Activity。

我想创建一个onItemClickedLongPress方法,这样当用户长按时,会弹出一个菜单。我很熟悉创建菜单的方法。

所以如果有人能提供进一步的说明,告诉我如何在ListFragment活动中设置重写长按操作?

4个回答

7

编辑:此示例演示如何显示系统菜单fx以外的内容。使用https://github.com/lorensiuswlt/NewQuickAction中的 QuickAction。

@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);
}

编辑:这个答案不好。为什么我要这样奇怪的方法呢?因为Eclipse智能提示没有提示ListView的第二个setOnLongClickListener方法(因为ListView至少有两个setOnLongClickListener方法,一个来自View类,另一个来自AdapterView类)... 最简单的方法是让您的ListFragment实现AdapterView.OnItemLongClickListener,然后在onViewCreated中添加代码getListView().setOnLongClickListener(this);


menuInfo 是 null?现在该怎么办? - Amit

5

如果您说的“长按”是指上下文菜单,那么对于一个 ListFragment,您只需要注册上下文菜单即可:

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

一旦您这样做了,ListFragment应该在检测到长按时调用onCreateContextMenu()onContextItemSelected()

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

0

进一步修改了Erich Douglass的答案...由于某种原因,直到我修改了代码并将注册放置在onViewCreated中,我的应用程序才不会崩溃:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接