首页 > 解决方案 > 我如何获取已安装的 Android 系统字体列表并应用于自定义键盘

问题描述

我必须制作一个可以检索预装 Android 操作系统的字体列表的应用程序。我需要显示系统字体,并且可以选择为我的应用程序设置该字体。

我的应用程序中有许多功能,我必须获取随机系统字体并将此字体样式应用于我的自定义软键盘。我如何将此字体应用于我的自定义软键盘。

我如何访问此字体并应用于我的应用程序?

标签: androidandroid-softkeyboardandroid-fonts

解决方案


加载系统字体的文件管理器类

public class FontManager {
    // This function enumerates all fonts on Android system and returns the HashMap with the font
    // absolute file name as key, and the font literal name (embedded into the font) as value.
    static public HashMap< String, String > enumerateFonts()
    {
        String[] fontdirs = { "/system/fonts", "/system/font", "/data/fonts" };
        HashMap< String, String > fonts = new HashMap< String, String >();
        TTFAnalyzer analyzer = new TTFAnalyzer();

        for ( String fontdir : fontdirs )
        {
            File dir = new File( fontdir );

            if ( !dir.exists() )
                continue;

            File[] files = dir.listFiles();

            if ( files == null )
                continue;

            for ( File file : files )
            {
                String fontname = analyzer.getTtfFontName( file.getAbsolutePath() );


                if ( fontname != null ) {
//                    Log.d("fonts", fontname+" : "+file.getAbsolutePath());
                    fonts.put(file.getAbsolutePath(), fontname);
                }

            }




        }

        return fonts.isEmpty() ? null : fonts;
    }

字体细节模型类:

public class FontDetail
{
    String sFontNames;
    String sFontPaths;
    String sFontType;

    public FontDetail(String sFontNames, String sFontPaths, String sFontType)
    {
        this.sFontNames = sFontNames;
        this.sFontPaths = sFontPaths;
        this.sFontType = sFontType;
    }

    public String getsFontNames()
    {
        return sFontNames;
    }

    public void setsFontNames(String sFontNames)
    {
        this.sFontNames = sFontNames;
    }

    public String getsFontPaths()
    {
        return sFontPaths;
    }

    public void setsFontPaths(String sFontPaths)
    {
        this.sFontPaths = sFontPaths;
    }

    public String getsFontType()
    {
        return sFontType;
    }

    public void setsFontType(String sFontType) {
        this.sFontType = sFontType;
    }
}

保存字体列表的数组列表:

   ArrayList<FontDetail> arrLstFontDetail = new ArrayList<FontDetail>();

在 arrLstFontDetails 中加载系统字体:

public void loadSystemFontsToListView() {
      try {
         Iterator<?> iter = FontManager.enumerateFonts().entrySet().iterator();

         while (iter.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry mEntry = (Map.Entry) iter.next();
            LogMaintain.ShowLog(LogMaintain.LogType.Error, "System : " + (String) mEntry.getValue() + "Key: " + (String) mEntry.getKey());
            arrLstFontDetail.add(new FontDetail((String) mEntry.getValue(), (String) mEntry.getKey(), "System"));
         }
}

推荐阅读