Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center text in a spinner in Android

Tags:

android

I have a Spinner in my LinearLayour.

I am trying to center text in spinner:

enter image description here

This is my XML for that element:

 <Spinner
    android:id="@+id/project_Spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginRight="50dp"
    android:layout_marginLeft="50dp"
    android:padding="1dip"


    android:prompt="@string/spinner_title"
/>

the declaration of the spinner in the Activity:

// Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, NomProjets);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);

Thanks,

like image 604
xtensa1408 Avatar asked Dec 12 '22 05:12

xtensa1408


2 Answers

The component that actually creates the items for the Spinner is the adapter. So you should customize it (by overriding the getView() method) to return centered TextView widgets.

In your case, replace the new ArrayAdapter<String> ... initialization with this code:

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, NomProjets)
{
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        return setCentered(super.getView(position, convertView, parent));
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent)
    {
        return setCentered(super.getDropDownView(position, convertView, parent));
    }

    private View setCentered(View view)
    {
        TextView textView = (TextView)view.findViewById(android.R.id.text1);
        textView.setGravity(Gravity.CENTER);
        return view;
    }
};
like image 171
matiash Avatar answered Jan 15 '23 01:01

matiash


Matiash's answer works. Here is another way:

Actually the text in the spinner is wrapped in a TextView , so we can override the android.R.layout.simple_spinner_item.xml(which is located at sdk\platforms\android-xx\data\res\layout) , create an new xml in the /layout folder, adding an attribute: android:gravity="center" to make the text in the TextView center.

such like this:

like image 25
drunkpiano Avatar answered Jan 15 '23 02:01

drunkpiano