searchview not expanding full width

jason picture jason · Oct 24, 2013 · Viewed 7.6k times · Source

Basically I want the searachview to expand and collapse when there is a imagebutton behind which should disappear when icon is clicked and view should appear when searchview collapses.

I am using search view not in action bar .When i click on the search icon it expands only half the screen but it should expand complete width but should wrap_content when I close the searchview.

<SearchView
        android:id="@+id/searchView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true">

I also tried :

android.view.ViewGroup.LayoutParams params = searchview.getLayoutParams();
params.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

But I am getting error here setLayoutParams it says "add to cast"

Answer

janox1x2x3 picture janox1x2x3 · Nov 4, 2013

At first you're getting an exception, because if you look into search_view.xml located in

\Android\android-sdk\platforms\android-18\data\res\layout\

You'll find out that SearchView is basically simple LinearLayout merging several widgets together. That's why you are getting class cast exception. Instead of

android.view.ViewGroup.LayoutParams params = searchview.getLayoutParams();

use

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) searchview.getLayoutParams();

or just import correct class and then you can simply use this

import android.widget.LinearLayout.LayoutParams;

                      ...

LayoutParams params = (LayoutParams) searchview.getLayoutParams();

than you can use LayoutParams without any prefix.

But I don't think that setting LayoutParams to wrap content will help. I would wrap your SearchView and ImageButton to RelativeLayout, where you could specify view position relative to the other views. Then simply set SearchView width to fill parent, so it could fill remaining space.