【问题标题】:How do I properly initiate a multi-select Contextual Action Bar for ListFragment (having issues)如何正确启动 ListFragment 的多选上下文操作栏(有问题)
【发布时间】:2013-03-04 08:02:28
【问题描述】:

我有一个ListFragment 与一个简单的ArrayAdapter 相关联。 ListView 包含一个可检查项的列表,其 XML 布局如下:

<ListView android:id="@id/android:list"
              android:layout_width="match_parent"
              android:layout_height="0dip"
              android:layout_weight="1"
              android:layout_marginLeft="2mm"
              android:layout_marginRight="2mm"
              android:drawSelectorOnTop="false"
              android:longClickable="true"
              android:choiceMode="multipleChoiceModal"/>

如您所见,我在 XML 布局中设置了 long-clickablechoicemode 属性。

我在ListFragmentonViewCreated回调中设置了合适的监听器:

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

    ListView list_view = getListView();
    list_view.setMultiChoiceModeListener(this);
    list_view.setOnItemLongClickListener(this);
}

我传入this 作为监听器参数,因为我的ListFragment 也实现了这些监听器的回调。

这是我遇到问题的回调:

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id
{
    activity.startActionMode(this);
    return true;
}

首先,onItemLongClick 永远不会被调用。 但是,当长按列表项时,上下文操作栏 (CAB) 会启动并完美运行!

事实上,CAB 在没有这个回调的情况下正确地启动了!我的回调使用activity.startActionMode(this),它会显示CAB,但不利于检查列表中的项目(我在其他地方测试过)。

如何以编程方式正确处理长点击以启动 CAB 并促进检查列表项?

我正在使用Android Developer Guide 主题中介绍的方法(他们使用了 onLongClickListener,我也尝试过但没有成功),但它似乎不起作用。

【问题讨论】:

    标签: android android-listview android-listfragment onlongclicklistener contextual-action-bar


    【解决方案1】:

    我猜你想出了这个,但是为了后代,你需要做的添加上下文菜单只是在你的根活动/片段下的 onContextMenuCreated 中添加上下文菜单项:

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
      if (v.getId()==R.id.list) {
        String[] menuItems = getResources().getStringArray(R.array.menu);
        for (int i = 0; i<menuItems.length; i++) {
          menu.add(Menu.NONE, i, i, menuItems[i]);
        }
      }
    }
    

    然后,响应onContextMenuCreated 下的上下文菜单点击。你可以在这里阅读更多:

    http://www.mikeplate.com/2010/01/21/show-a-context-menu-for-long-clicks-in-an-android-listview/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多