Android:到处使用自定义字体(示例)
Zas12357386
・4 分钟阅读
Android不提供在应用程序的所有区域中使用定制字体文件(TTF,otf等)的机制,相反,必须使用策略在所有TextView,EditText和Button设置定制的Typeface 。
这篇文章涵盖了应对常见应用需求的策略。
视图爬虫
Android中的布局(还有sub-layouts )是由ViewGroup
作为复合元素,View
为叶子节点的树层次结构,可以通过在你喜欢的(广度优先或深度优先)中访问子视图来抓取此树,爬这棵树的时候你可以在任何TextView
上替换所有的,和所遇到的Button
。
下面是一个视图爬虫的简单递归实现,它将替换层次结构中任何适当视图的Typeface
:
public class FontChangeCrawler
{
private Typeface typeface;
public FontChangeCrawler(Typeface typeface)
{
this.typeface = typeface;
}
public FontChangeCrawler(AssetManager assets, String assetsFontFileName)
{
typeface = Typeface.createFromAsset(assets, assetsFontFileName);
}
public void replaceFonts(ViewGroup viewTree)
{
View child;
for(int i = 0; i <viewTree.getChildCount(); ++i)
{
child = viewTree.getChildAt(i);
if(child instanceof ViewGroup)
{
//recursive call
replaceFonts((ViewGroup)child);
}
else if(child instanceof TextView)
{
//base case
((TextView) child).setTypeface(typeface);
}
}
}
}
替换Activity的整个字体
要替换Activity布局中每个视图中的默认字体,只需使用上面的FontChangeCrawler,就像这样:
@Override
public void setContentView(View view)
{
super.setContentView(view);
FontChangeCrawler fontChanger = new FontChangeCrawler(getAssets()," font.otf" );
fontChanger.replaceFonts((ViewGroup)this.findViewById(android.R.id.content));
}
如果你不熟悉android.R.id.content
,它是在Activity
布局中给View
的官方标识。
考虑将上述逻辑放在BaseActivity
类中。
替换字体
你还需要对每个Fragment
应用FontChangeCrawler
,请考虑将此逻辑放入BaseFragment
类。
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
FontChangeCrawler fontChanger = new FontChangeCrawler(getAssets()," font.otf" );
fontChanger.replaceFonts((ViewGroup) this.getView());
}
处理Adapter等,
替换Activity字体很长,但是,大多数人还有很多ListView ,在ListView
中的列表项是在适配器内构建的,而不是在Activity
中生成的,因此,你还需要在适配器中使用FontChangeCrawler
:
...
if(convertView == null)
{
convertView = inflater.inflate(R.layout.listitem, null);
fontChanger.replaceFonts((ViewGroup)convertView);
}
...