I have a Spinner in my LinearLayour.
I am trying to center text in spinner:
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,
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;
}
};
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With