How to handle onContextItemSelected in a multi fragment activity?

前端 未结 11 2095
天命终不由人
天命终不由人 2020-11-29 17:26

I\'m currently trying to adapt my application to use the \"Compatibility Libraries for Android v4\" to provide the benefits of the usage of fragments even to Android 1.6 use

11条回答
  •  借酒劲吻你
    2020-11-29 18:04

    IMHO we may just check if target view is child of fragment listview. It is very simple and work for me well. I just added to all my fragments:if (getListView.getPositionForView(info.targetView) == -1) return false when migrate from older API

    This is example from one of my parent fragments. This is Scala, but I hope you got an idea.

    @Loggable
    override def onContextItemSelected(menuItem: MenuItem): Boolean = {
      for {
        filterBlock <- TabContent.filterBlock
        optionBlock <- TabContent.optionBlock
        environmentBlock <- TabContent.environmentBlock
        componentBlock <- TabContent.componentBlock
      } yield menuItem.getMenuInfo match {
      case info: AdapterContextMenuInfo =>
        if (getListView.getPositionForView(info.targetView) == -1)
          return false
        TabContent.adapter.getItem(info.position) match {
          case item: FilterBlock.Item =>
            filterBlock.onContextItemSelected(menuItem, item)
          case item: OptionBlock.Item =>
            optionBlock.onContextItemSelected(menuItem, item)
          case item: EnvironmentBlock.Item =>
            environmentBlock.onContextItemSelected(menuItem, item)
          case item: ComponentBlock.Item =>
            componentBlock.onContextItemSelected(menuItem, item)
          case item =>
            log.debug("skip unknown context menu item " + info.targetView)
            false
        }
      case info =>
        log.fatal("unsupported menu info " + info)
        false
      }
    } getOrElse false
    

    P.S. If you trace calls of onContextItemSelected(...) you may notify that super.onContextItemSelected(item) return always false. Valid onContextItemSelected invoked AFTER, not WITHIN. So super.onContextItemSelected(item) is useless and I replaced it with false.

提交回复
热议问题