【问题标题】:How do I override up button behavior in search view如何覆盖搜索视图中的向上按钮行为
【发布时间】:2015-12-10 18:24:27
【问题描述】:

我已经像 YouTube 应用一样在单独的片段中实现了 searchView。因此,当用户单击搜索图标时,新片段会启动并展开搜索视图。

现在,如果现在单击向上按钮,则搜索视图将折叠。只有当再次单击向上按钮时,才会从后堆栈中显示上一个片段。

我需要做的是,当用户从展开的搜索视图状态单击向上按钮时,搜索片段会立即关闭并出现前一个片段。

任何帮助表示赞赏。

更新

我找到了几乎可行的解决方案:

    MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            Log.d(LOG_TAG, "onMenuItemActionCollapse");
            onBackPressed();
            return true;  // Return true to collapse action view
        }

        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            // Do something when expanded
            return true;  // Return true to expand action view
        }
    });

但是这个解决方案有一个大问题:如果在搜索视图文本字段中有文本时按下返回箭头按钮,那么

java.lang.IllegalStateException: Fragment SearchFragment not attach to Activity 被抛出。

为什么会发生这种异常以及如何避免它?

【问题讨论】:

    标签: android android-fragments searchview


    【解决方案1】:

    在您的活动/片段中覆盖 onOptionsItemSelected()。向上按钮的 ID 为“android.R.id.home”

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                case android.R.id.home:
                    //Handle Up button
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
                }
            }
    

    【讨论】:

      【解决方案2】:
      mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
          @Override    
          public boolean onClose() {
              getFragmentManager().popBackStack(); // Or other mechanism, depends on what you have.
              return false; // Don't consume event, will dismiss search.
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2016-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-14
        • 2015-07-20
        相关资源
        最近更新 更多