set view text align at center in spinner in android

Pratik picture Pratik · Sep 22, 2011 · Viewed 88.7k times · Source

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

Answer

Andro Selva picture Andro Selva · Sep 22, 2011

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);