如何让用户决定按钮的字体?

时间:2018-07-29 08:42:44

标签: java android fonts colors styles

代码

Button mButton1;
int mDefaultColor1;
SharedPreferences mSharedPreferences1;
SharedPreferences.Editor editor1;

 mButton1 = (Button)findViewById(R.id.buttontextfontsent);
    mSharedPreferences1 = PreferenceManager.getDefaultSharedPreferences(this);
    mDefaultColor1 = mSharedPreferences1.getInt("Default_Color1",ContextCompat.getColor(CustomizeFont.this,R.color.white));
    mButton1.setBackgroundColor(mDefaultColor1);

选色后

editor2 = PreferenceManager.getDefaultSharedPreferences(CustomizeColor.this).edit();
            editor2.putInt("Default_Color2", color);
            editor2.apply();
        }

这就是我用来让用户更改按钮颜色的方法...我也想对字体进行同样的操作...但是遇到困难...任何人都可以帮助我吗?我想为此使用sharedpreferences。

2 个答案:

答案 0 :(得分:0)

在“ src”中创建一个名为“ Assets”的文件夹。将font(.ttf)文件复制到Assets文件夹并使用:

Button button=(Button) findViewById(R.id.enter);
Typeface type=Typeface.createFromAsset(getAssets(), "arial.ttf");
button.setTypeface(type);

答案 1 :(得分:0)

以与颜色相同的方式进行操作,只需要将字体另存为字符串即可。

在首选项中保存字体

editor.putString("font","selected_font")

从首选项取回

String fontName = editor.getString("font","default_font");
// make sure fontName is available under assets->fonts
Typeface typeface = Typeface.createFromAsset(context.getAssets(), String.format("fonts/%s.ttf", name));
// Preferred way
Typeface typeface = Typefaces.get(getContext(), name));

将字体应用于视图

button.setTypeface(typeface);

这是优化部分,它避免了昂贵的字体创建过程。

class Typefaces {

  private static final Hashtable<String, Typeface> FONT_CACHE = new Hashtable<>();

  public static Typeface get(Context context, String name) {
      if (!FONT_CACHE.containsKey(name)) {
          Typeface typeface = Typeface.createFromAsset(context.getAssets(), String.format("fonts/%s.ttf", name));
        FONT_CACHE.put(name, typeface);
      }
      return FONT_CACHE.get(name);
  }

}
相关问题