Nil*_*hal 91 java xml fonts android android-layout
我已将自定义字体文件添加到我的assets/fonts文件夹中.如何从我的XML中使用它?
我可以从代码中使用它如下:
TextView text = (TextView) findViewById(R.id.textview03);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Molot.otf");
text.setTypeface(tf);
Run Code Online (Sandbox Code Playgroud)
我不能使用android:typeface="/fonts/Molot.otf"属性从XML做到吗?
the*_*hal 44
简短回答:不会.Android没有内置支持通过XML将自定义字体应用于文本小部件.
但是,有一种解决方法并不是非常难以实现.
第一
您需要定义自己的样式.在/ res/values文件夹中,打开/创建attrs.xml文件并添加一个声明样式的对象,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FontText">
<attr name="typefaceAsset" format="string"/>
</declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)
第二
假设您经常要使用此窗口小部件,则应为加载的Typeface对象设置一个简单缓存,因为在运行中从内存中加载它们可能需要一些时间.就像是:
public class FontManager {
private static FontManager instance;
private AssetManager mgr;
private Map<String, Typeface> fonts;
private FontManager(AssetManager _mgr) {
mgr = _mgr;
fonts = new HashMap<String, Typeface>();
}
public static void init(AssetManager mgr) {
instance = new FontManager(mgr);
}
public static FontManager getInstance() {
if (instance == null) {
// App.getContext() is just one way to get a Context here
// getContext() is just a method in an Application subclass
// that returns the application context
AssetManager assetManager = App.getContext().getAssets();
init(assetManager);
}
return instance;
}
public Typeface getFont(String asset) {
if (fonts.containsKey(asset))
return fonts.get(asset);
Typeface font = null;
try {
font = Typeface.createFromAsset(mgr, asset);
fonts.put(asset, font);
} catch (Exception e) {
}
if (font == null) {
try {
String fixedAsset = fixAssetFilename(asset);
font = Typeface.createFromAsset(mgr, fixedAsset);
fonts.put(asset, font);
fonts.put(fixedAsset, font);
} catch (Exception e) {
}
}
return font;
}
private String fixAssetFilename(String asset) {
// Empty font filename?
// Just return it. We can't help.
if (TextUtils.isEmpty(asset))
return asset;
// Make sure that the font ends in '.ttf' or '.ttc'
if ((!asset.endsWith(".ttf")) && (!asset.endsWith(".ttc")))
asset = String.format("%s.ttf", asset);
return asset;
}
}
Run Code Online (Sandbox Code Playgroud)
这个允许你使用.ttc文件扩展名,但它没有经过测试.
第三
创建一个子类的新类TextView.此特定示例考虑了已定义的XML字体(bold,italic等)并将其应用于字体(假设您使用的是.ttc文件).
/**
* TextView subclass which allows the user to define a truetype font file to use as the view's typeface.
*/
public class FontText extends TextView {
public FontText(Context context) {
this(context, null);
}
public FontText(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FontText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (isInEditMode())
return;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.FontText);
if (ta != null) {
String fontAsset = ta.getString(R.styleable.FontText_typefaceAsset);
if (!TextUtils.isEmpty(fontAsset)) {
Typeface tf = FontManager.getInstance().getFont(fontAsset);
int style = Typeface.NORMAL;
float size = getTextSize();
if (getTypeface() != null)
style = getTypeface().getStyle();
if (tf != null)
setTypeface(tf, style);
else
Log.d("FontText", String.format("Could not create a font from asset: %s", fontAsset));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后
使用TextView完全限定的类名替换XML中的实例.像Android命名空间一样声明自定义命名空间.请注意,"typefaceAsset"应指向/ assets目录中包含的.ttf或.ttc文件.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.FontText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a custom font text"
custom:typefaceAsset="fonts/AvenirNext-Regular.ttf"/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
小智 28
这是执行此操作的示例代码.我在静态最终变量中定义了字体,字体文件在assets目录中.
public class TextViewWithFont extends TextView {
public TextViewWithFont(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTypeface(MainActivity.typeface);
}
public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setTypeface(MainActivity.typeface);
}
public TextViewWithFont(Context context) {
super(context);
this.setTypeface(MainActivity.typeface);
}
}
Run Code Online (Sandbox Code Playgroud)
hao*_*ang 13
创建属于您要使用的字体的自定义TextView.在这个类中,我使用静态mTypeface字段来缓存Typeface(为了更好的性能)
public class HeliVnTextView extends TextView {
/*
* Caches typefaces based on their file path and name, so that they don't have to be created every time when they are referenced.
*/
private static Typeface mTypeface;
public HeliVnTextView(final Context context) {
this(context, null);
}
public HeliVnTextView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public HeliVnTextView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getAssets(), "HelveticaiDesignVnLt.ttf");
}
setTypeface(mTypeface);
}
}
Run Code Online (Sandbox Code Playgroud)
在xml文件中:
<java.example.HeliVnTextView
android:id="@+id/textView1"
android:layout_width="0dp"
... />
Run Code Online (Sandbox Code Playgroud)
在java类中:
HeliVnTextView title = new HeliVnTextView(getActivity());
title.setText(issue.getName());
Run Code Online (Sandbox Code Playgroud)
Leo*_*Leo 11
Activity实现了LayoutInflater.Factory2,它为每个创建的View提供回调.可以使用自定义字体Family属性设置TextView的样式,根据需要加载字体并自动在实例化的文本视图上调用setTypeface.
不幸的是,由于Inflater实例相对于Activities和Windows的架构关系,在android中使用自定义字体的最简单方法是在应用程序级别缓存加载的字体.
示例代码库位于:
https://github.com/leok7v/android-textview-custom-fonts
<style name="Baroque" parent="@android:style/TextAppearance.Medium">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#F2BAD0</item>
<item name="android:textSize">14pt</item>
<item name="fontFamily">baroque_script</item>
</style>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/custom.fonts"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
style="@style/Baroque"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/sample_text"
/>
Run Code Online (Sandbox Code Playgroud)
结果是

更新:https://github.com/chrisjenx/Calligraphy似乎是一个很好的解决方案.
也许您可以在创建应用程序时使用反射将您的字体注入/破解到可用字体的静态列表中?我对其他人的反馈感兴趣,如果这是一个非常非常糟糕的想法,或者这是一个很好的解决方案 - 它似乎将成为极端的一个......
我能够使用我自己的字体系列名称将我的自定义字体注入系统字体列表,然后将标准TextView上的自定义字体系列名称("brush-script")指定为android:FontFamily的值.G4运行Android 6.0.
public class MyApplication extends android.app.Application
{
@Override
public void onCreate()
{
super.onCreate();
Typeface font = Typeface.createFromAsset(this.getResources().getAssets(),"fonts/brush-script.ttf");
injectTypeface("brush-script", font);
}
private boolean injectTypeface(String fontFamily, Typeface typeface)
{
try
{
Field field = Typeface.class.getDeclaredField("sSystemFontMap");
field.setAccessible(true);
Object fieldValue = field.get(null);
Map<String, Typeface> map = (Map<String, Typeface>) fieldValue;
map.put(fontFamily, typeface);
return true;
}
catch (Exception e)
{
Log.e("Font-Injection", "Failed to inject typeface.", e);
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的布局
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fancy Text"
android:fontFamily="brush-script"/>
Run Code Online (Sandbox Code Playgroud)
在资产中创建一个字体文件夹,并在那里添加所有需要的字体。
public class CustomTextView extends TextView {
private static final String TAG = "TextView";
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
String customFont = a.getString(R.styleable.CustomTextView_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String fontName) {
Typeface typeface = null;
try {
if(fontName == null){
fontName = Constants.DEFAULT_FONT_NAME;
}
typeface = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + fontName);
} catch (Exception e) {
Log.e(TAG, "Unable to load typeface: "+e.getMessage());
return false;
}
setTypeface(typeface);
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
并在attrs.xml 中添加一个declarable
<declare-styleable name="CustomTextView">
<attr name="customFont" format="string"/>
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
然后添加您的自定义字体,例如
app:customFont="arial.ttf"
Run Code Online (Sandbox Code Playgroud)
我知道这是一个老问题,但我找到了一个更简单的解决方案。
首先像往常一样在 xml 中声明你的 TextView。将您的字体(TTF 或 TTC)放在资产文件夹中
应用程序\src\main\assets\
然后只需在 onCreate 方法中为文本视图设置字体。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name);
TextView textView = findViewById(R.id.my_textView);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fontName.ttf");
textView.setTypeface(typeface);
}
Run Code Online (Sandbox Code Playgroud)
完毕。
| 归档时间: |
|
| 查看次数: |
127075 次 |
| 最近记录: |