Question

I'm doing one demo. In that I'm loading the system fonts into the Spinner and I want to set the selected font to TextView. I done with font loading but I'm not able to set it to TextView. I'm confused with the TypeFace ... Following is my code..

        package com.example.accessingsystemfonts;

    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;

    import android.app.Activity;
    import android.graphics.Typeface;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.Spinner;
    import android.widget.TextView;

    public class MainActivity extends Activity {
    TextView tv;
    Button b1;
    Spinner sp1;
    List<String> fontNames ;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tv=(TextView)findViewById(R.id.tv);
            b1=(Button)findViewById(R.id.buttonset);
            sp1=(Spinner)findViewById(R.id.spinnersystemfonts);
            readAllFonts();
            b1.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                   tv.setTypeface(?);   **How to set selected font??**

                }
            });
        }



       private List<String> readAllFonts() {

        fontNames = new ArrayList<String>();

        File temp = new File("/system/fonts/");

        String fontSuffix = ".ttf";

        for(File font : temp.listFiles()){  

            String fontName = font.getName();

            if(fontName.endsWith(fontSuffix)) {

                fontNames.add(fontName.subSequence(0,fontName.lastIndexOf(fontSuffix)).toString());

            }
           }
         sp1.setAdapter(new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_spinner_dropdown_item,fontNames));
        return fontNames;
     } 
    }
Was it helpful?

Solution

This should work for you

tv.setTypeface(Typeface.createFromFile("/system/fonts/" + sp1.getSelectedItem().toString() + ".ttf"));

You may need to tweak how you are getting the selected font text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top