Android Spinner Size very large
Asked Answered
L

1

9

I'm trying to get an ICS spinner like in my app, and playing around for hours, finally I'm using HoloEverywhere to get this, and it's working, but I have a little disign issue, is that the spinner is not wrapping its content as I set in the xml, and by default looks like this :

enter image description here

Really I googled this for hours, and all I found is that how to resize spinner items and not the view itself, means that I want the spinner to be adjusted to the selected item size like this :

Here is my XML:

<RelativeLayout 
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal" >

<org.holoeverywhere.widget.Spinner
    android:id="@+id/spnCities"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="10dp"
    />

<TextView
    android:id="@+id/tvCities"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginLeft="10dp"
    android:text="@string/city"
    android:textAppearance="?android:attr/textAppearanceSmall" />

</RelativeLayout>
Lambent answered 19/12, 2012 at 14:51 Comment(0)
G
6

Spinner have max width his items, but at most a parent width (on layout_width = wrap_content). You may create CustomSpinner class in org.holoeverywhere.widget package and override method measureContentWidth:

@Override
int measureContentWidth(SpinnerAdapter adapter, Drawable background) {
    if (adapter == null) {
        return 0;
    }
    View view = adapter.getView(getSelectedItemPosition(), null, this);
    if (view.getLayoutParams() == null) {
        view.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
    }
    view.measure(MeasureSpec.makeMeasureSpec(0,
            MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0,
            MeasureSpec.UNSPECIFIED));
    int width = view.getMeasuredWidth();
    if (background != null) {
        Rect mTempRect = new Rect();
        background.getPadding(mTempRect);
        width += mTempRect.left + mTempRect.right;
    }
    return width;
}
Gouveia answered 20/12, 2012 at 8:11 Comment(1)
This also worked for me ! Creating your own CustomSpinner and just implemeting that method (without the override) and using ir in your app the width of the item selected just has his real with :) in previous versions the spinner by default do this, at least 2.3Baumbaugh

© 2022 - 2024 — McMap. All rights reserved.