Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the text style of a spinner?

I'm creating a spinner in my layout xml files and setting an string array to this spinner. If I change the textstyle of the spinner the text is not affected by the changes.

I read in the googlegroups that a spinner has no text and therefore the textstyle can not be changed and I have to change the style of the textview that is shown in the spinner. But how can I do that. Preferably in my xml file.

like image 690
Janusz Avatar asked Jul 08 '10 15:07

Janusz


People also ask

How do I change the font of the spinner family?

In summary to change the text size (or other style attributes) for a Spinner either: Create a custom TextView layout. Change the text size with the android:textSize attribute. Change the text color with android:textColor.


1 Answers

As my predecessor specified, you can't do it on the main XML layout file where the Spinner component is.

And the answer above is nice, but if we want to use Google's best practices, like you know... to use styles for everything... you could do it in 3 'easy' steps as follows:

Step 1: You need an extra file under your layout folder with the look for the Spinner's items:

<?xml version="1.0" encoding="utf-8"?>
<TextView  
    android:id="@+id/textViewSpinnerItem" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    style="@style/SpinnerTextViewItem"
    xmlns:android="http://schemas.android.com/apk/res/android" />

Name this file: spinner_item_text.xml

Step 2: Then, on your Activity Class when you are filling the Spinner with an array of items:

adapter = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item_text, items);
spinner.setAdapter(adapter);

Note that the R.layout.spinner_item_text resource is in your own R's file.

Step 3: Under your values folder, create or use (you might have one already) the file styles.xml. The style entry needed should look like this one:

<style name="SpinnerTextViewItem" parent="@android:style/Widget.TextView" >
    <item name="android:textSize" >8dp</item>
    <item name="android:textStyle" >bold</item>
</style>

And that's it!

So far it has been really, really handy to put all about text sizes, styles, colors, etc... on a styles.xml file so it's easy to maintain.

like image 182
Oscar Salguero Avatar answered Oct 03 '22 09:10

Oscar Salguero