set view text align at center in spinner in android

view-text-in-the-center-of-the-spinner-when-select-from-the-drop-down-list

I want to align the view text of spinner to center. I google it but didn't find anything, does anybody knows about this? any help or suggestion are appreciated


Create a adapter for your spinner like this,

ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.my_spinner_style,array_of_values) {

    public View getView(int position, View convertView,ViewGroup parent) {

        View v = super.getView(position, convertView, parent);

        ((TextView) v).setTextSize(16);

        return v;

    }

    public View getDropDownView(int position, View convertView,ViewGroup parent) {

        View v = super.getDropDownView(position, convertView,parent);

        ((TextView) v).setGravity(Gravity.CENTER);

        return v;

    }

};

Now your layout R.layout.my_spinner_style,

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:textColor="#ffffff"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" />

Now set this adapter to your spinner,

spinner.setAdapter(adapter);

You need to set your own layout for spinner item.

SpinnerAdapter adap = new ArrayAdapter<String>(this, R.layout.spinner_item, new String[]{"A", "B", "C"});
spriner.setAdapter(adap);

Where R.layout.spinner_item is a layout with content:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="fill_parent"
    android:layout_width="fill_parent" 
    android:gravity="center" 
    android:textColor="#000000" 
    android:text="Sample Text" 
    android:paddingBottom="5dp" 
    android:paddingTop="5dp"></TextView>

This is very simple. Just create a xml file named as, for example, spinner_item.xml with content as

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#111111"
android:padding="10dp"
android:textAlignment="center"
/>

Now in your Java class, instead of adding Android's default view resource add your custom view resource as

ArrayAdapter<String> adapter= new ArrayAdapter<String>(context, R.layout.spinner_item, myList);
 adapter.setDropDownViewResource(R.layout.spinner_item);

The textAlignment line will do the trick.