Wil*_* L. 51 fonts android textview typeface
是否可以为活动中的所有TextView设置字体?我可以使用以下方法设置单个textView的字体:
TextView tv=(TextView)findViewById(R.id.textView1);
Typeface face=Typeface.createFromAsset(getAssets(), "font.ttf");
tv.setTypeface(face);
Run Code Online (Sandbox Code Playgroud)
但我想一次更改所有textViews,而不是为每个textView手动设置,任何信息都将不胜感激!
Sha*_*wal 90
Solution1 ::只需将父视图作为参数传递,即可调用这些方法.
private void overrideFonts(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
overrideFonts(context, child);
}
} else if (v instanceof TextView ) {
((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "font.ttf"));
}
} catch (Exception e) {
}
}
Run Code Online (Sandbox Code Playgroud)
Solution2 ::您可以使用自定义字体继承TextView类,并使用它而不是textview.
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font.ttf");
setTypeface(tf);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我个人收藏的那个:
private void setFontForContainer(ViewGroup contentLayout) {
for (int i=0; i < contentLayout.getChildCount(); i++) {
View view = contentLayout.getChildAt(i);
if (view instanceof TextView)
((TextView)view).setTypeface(yourFont);
else if (view instanceof ViewGroup)
setFontForContainer((ViewGroup) view);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37794 次 |
| 最近记录: |