How to right-align Android spinner

greysqrl picture greysqrl · Jan 6, 2016 · Viewed 10k times · Source

I'm trying to right-align the text of an Android spinner. I have been through Stack Overflow and tried the recommended solution but it's not working for me so, I'm a little confused as to what I have done wrong. My feeling is that my layout is not being correctly picked up due to an error I have made.

My activity.xml file

<Spinner
android:id="@+id/spinnerStoreType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>

Under res\layout I have created a file called simple_spinner_item.xml

<?xml version="1.0" encoding="utf-8"?>

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="40sp"
    android:textColor="#FFFFFF"
    android:padding="10dip"
    android:gravity="right"
    />

Finally, in my activity I am using this as follows:

spinnerStoreType = (Spinner) findViewById(R.id.spinnerStoreType);
ArrayAdapter<CharSequence> adapter =    
ArrayAdapter.createFromResource(this,
R.array.transaction_store_array, android.R.layout.simple_spinner_item);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinnerStoreType.setAdapter(adapter);

So, I believe that the simple_spinner_item being used is the default one, Android's one. I'm unclear how to get it to use my custom one. I thought that would happen automatically if it has the same name?

Any help as always is very much appreciated.

Answer

Sanjeet A picture Sanjeet A · Jan 6, 2016

You can achieve this completely using the styles. And I think that's the best way. Here is the code from my styles.xml-

    <style name="AppTheme.Spinner">
        <item name="android:spinnerItemStyle">@style/SpinnerItem</item>
        <item name="android:spinnerDropDownItemStyle">@style/SpinnerDropDownItem</item>
    </style>

    <style name="SpinnerItem">
        <item name="android:gravity">right|center_vertical</item>
        <item name="android:paddingRight">16dp</item>
    </style>

    <style name="SpinnerDropDownItem">
        <item name="android:gravity">right|center_vertical</item>
        <item name="android:paddingRight">16dp</item>
    </style>

and here is the implementation to a spinner-

       <Spinner
            android:id="@+id/type"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_below="@id/title"
            android:entries="@array/data"
            android:theme="@style/AppTheme.Spinner" />