【问题标题】:How to animate full width SearchView expand/collapse in action bar?如何在操作栏中为全宽 SearchView 展开/折叠设置动画?
【发布时间】:2015-05-07 20:53:48
【问题描述】:

我正在使用来自support.v7 库的SearchView。我查看了this post,这表明您可以通过设置LayoutTransition 来简单地为搜索视图设置动画

LinearLayout searchBar = (LinearLayout) searchView.findViewById(searchBarId);
//Give the Linearlayout a transition animation.
searchBar.setLayoutTransition(new LayoutTransition()); 

但是以上方法对我不起作用。搜索视图似乎也只填充了横向 中的部分屏幕宽度。我想要它fill_parent

我试图通过创建一个简单的动画来解决这两个问题,但在searchView.getLayoutParams(); 失败了,因为它似乎总是返回 null。

最终目标是在操作栏中有一个 SearchView 可以平滑地展开/折叠并占据横向屏幕宽度的宽度。

有没有办法做到这一点?

这是我目前拥有的搜索视图设置:

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        //Associate searchable configuration with the SearchView
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.search));
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        //Returns null
        //searchView.getLayoutParams();
        return true;
    }

还有menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".MainActivity">
      <item android:id="@+id/search"
            android:title="Search"
            android:icon="@android:drawable/ic_menu_search"
            app:showAsAction="collapseActionView|ifRoom"
            app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

【问题讨论】:

  • 更新为包含菜单 xml。

标签: android android-support-library searchview android-actionbar-compat


【解决方案1】:

在 oncreateoptions 中做:

MenuItem searchitem = menu.findItem(R.id.search);
SearchView search= (SearchView) searchitem.getActionView();
ActionBar.LayoutParams p= new ActionBar.LayoutParams(ActionBar.LayoutParams.MATch_parent, same here)
search.setLayoutParams(p);
searchitem.expandActionView();

【讨论】:

  • 这使用了我的帖子中提到的 android.app.ActionBar 我正在使用支持 v7 库。这似乎对我不起作用。我使用了您答案的支持版本。横向测试过吗?扩展的搜索视图在横向上仍然没有占据我的整个宽度。
  • 有什么理由不使用 ActionBar ?
  • 是的,我没有使用 android.app.Activity,所以我无法访问常规操作栏。我正在使用支持库来向后兼容某些功能。
猜你喜欢
  • 2013-10-30
  • 2011-03-17
  • 2021-03-25
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
相关资源
最近更新 更多