将选定的系统字体设置为TextView

时间:2014-02-26 11:03:23

标签: android fonts spinner android-arrayadapter typeface

我正在做一个演示。我正在将系统字体加载到Spinner中,我想将所选字体设置为TextView。我完成了字体加载,但我无法将其设置为TextView。我对TypeFace感到困惑...... 以下是我的代码..

        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;
     } 
    }

1 个答案:

答案 0 :(得分:1)

这应该对你有用

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

您可能需要调整获取所选字体文本的方式。