8

I am having a spinner with a simple list in it. I want to know whether I could replace the style of the font in my spinner. Or is there anyway that I could make use to change the font style,size and color.

Any clearance given is much appreciated.

Andro Selva
  • 53,910
  • 52
  • 193
  • 240

1 Answers1

7

Didn't try it, but android:typeface in XML or setTypeface() in code should work.

EDIT: Please follow the guidance here.

First, create a new XML file in your res/layout directory called "my_spinner_style.xml", and put in something like the following content:

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="9pt"
android:singleLine="True"
android:id="@+id/spinnerTarget"
android:textColor="#000000"
android:gravity="center"/>

Then in your code, use something like this:

Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
mySpinnerArrayAdapter = new MyCustomArrayAdapter(this, R.layout.my_spinner_style);  
mySpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Normally you would create a new ArrayAdapter for the second line, but in this case you need to create a custom ArrayAdapter and override the methods that get the TextView from our custom spinner style.

So, you need to put in the code for your custom ArrayAdapter, like so:

private class MyArrayAdapter extends ArrayAdapter {

    public MyArrayAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    public TextView getView(int position, View convertView, ViewGroup parent) {
        TextView v = (TextView) super.getView(position, convertView, parent);
        v.setTypeface(myFont);
        return v;
    }

    public TextView getDropDownView(int position, View convertView, ViewGroup parent) {
        TextView v = (TextView) super.getView(position, convertView, parent);
        v.setTypeface(myFont);
        return v;
    }

}

The font you want to use needs to reside in the assets/fonts directory, and you access it like so:

Typeface myFont = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");

And that's pretty much it.

doplumi
  • 2,938
  • 4
  • 29
  • 45
Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
  • 1
    That is what my problem is. There is no android:typeface in spinner. – Andro Selva May 23 '11 at 06:44
  • 4
    Right. The solution is more convoluted than I thought. I found some workarounds [here](http://polyclefsoftware.blogspot.com/2009/06/how-to-change-your-spinner-typeface.html) and [here](http://stackoverflow.com/questions/3901231/how-to-change-font-style-for-spinner-item). I hope this helps. – Gabriel Negut May 23 '11 at 07:07
  • That was cool.. Thanks. What I was expecting. – Andro Selva May 23 '11 at 07:22