Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SearchView expand/collapse animation in Android

What I Have

I have a SearchView which does its work perfectly. But when I touch on it, it appears and disappears out of nothing. There is no transition animation playing on it and so it doesn't look good.

What I Want

I want a simple slide left and slide right animation to be played on the SearchView when it is expanded and collapsed respectively.

What I Tried

SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
//Get the ID for the search bar LinearLayout
int searchBarId = searchView.getContext().getResources().getIdentifier("android:id/search_bar", null, null);
//Get the search bar Linearlayout
LinearLayout searchBar = (LinearLayout) searchView.findViewById(searchBarId);
//Give the Linearlayout a transition animation.
searchBar.setLayoutTransition(new LayoutTransition());

but the searchBar is always null so I can't set the layout transition on it.

Can I get a solution for it? Is my approach correct?

like image 576
Aritra Roy Avatar asked Jul 03 '15 16:07

Aritra Roy


2 Answers

You can actually just grab the LinearLayout by doing the following:

LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar);

So this is what you should write instead,

SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
final int searchBarId = searchView.getContext().getResources().getIdentifier("android:id/search_bar", null, null);  // Remove this line 

//  The modified Line
LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar);  

searchBar.setLayoutTransition(new LayoutTransition());
like image 89
Steven Avatar answered Oct 06 '22 20:10

Steven


After reading the @Steven answer I got the solution given below

inside the onCreateOptionsMenu(Menu menu) method write the code

    getMenuInflater().inflate(R.menu.meet_people_menu, menu);
    final MenuItem searchItem = menu.findItem(R.id.app_bar_search);
    SearchView searchView = (SearchView) searchItem.getActionView();
    LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar);
    searchBar.setLayoutTransition(new LayoutTransition());

and here is my meet_people_menu.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="com.jz.cso.activities.MeetPeopleActivity">
<item
    android:title=""
    android:id="@+id/app_bar_search"
    android:icon="@drawable/ic_search_black_24dp"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always"
    ></item>
</menu>
like image 39
Umar Ata Avatar answered Oct 06 '22 18:10

Umar Ata