长按ListFragment

时间:2011-07-18 12:05:15

标签: android android-fragments long-click

我正在使用ListFragment并执行onListItemClick。一切正常,但现在我想使用一个长项目点击(例如setOnItemLongClickListener(一个活动的新OnItemLongClickListener())。我如何在我的片段中使用它?

谢谢!

3 个答案:

答案 0 :(得分:59)

是的,tsync发布的解决方案对我有用。我也遇到了同样的问题,并认为这是不可能的。我尝试了以上建议如下:

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

它有效!

答案 1 :(得分:13)

根据您想要实现的内容,您可以将给定的方法用于上下文菜单:

首先注册长期按下的View类(在Fragment类中):

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

    registerForContextMenu(this.getListView());
}

要实现这两种方法,要创建上下文菜单,并在单击菜单项时执行任何操作:

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

答案 2 :(得分:11)

这对我有用

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