本范例实现的是对界面中所有的控件一次性的设置字体样式。思路是找到父控件,然后遍历子控件。如果子控件是可以修改文字的控件,那么就设置文字。这用到了控件的继承,很多控件都是继承与textview的,所以将控件均转为textview,最后设置字体即可。
布局文件
MainActivity
package com.kale.font;import android.app.Activity;import android.graphics.Typeface;import android.os.Bundle;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.EditText;import android.widget.SeekBar;import android.widget.SeekBar.OnSeekBarChangeListener;import android.widget.TextView;public class MainActivity extends Activity { private static int FLAG = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Sets fonts for all final Typeface mFont = Typeface.createFromAsset(getAssets(), "Roboto-Thin.ttf"); final ViewGroup root = (ViewGroup) findViewById(R.id.layout); setFont(root, mFont,16); FLAG = 1;//初始化完成后标志位为1,滑动滑块只修改字体大小。不重复指定字体了。 ((SeekBar) findViewById(R.id.seekBar)).setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { setFont(root, mFont,progress); } }); } /* * Sets the font on all TextViews in the ViewGroup. Searches recursively for * all inner ViewGroups as well. Just add a check for any other views you * want to set as well (EditText, etc.) */ public void setFont(ViewGroup group, Typeface font ,int textSize) { int count = group.getChildCount(); View v; for (int i = 0; i < count; i++) { v = group.getChildAt(i); if (v instanceof TextView || v instanceof EditText || v instanceof Button) { if (FLAG == 0) { ((TextView) v).setTypeface(font); } ((TextView)v).setTextSize(textSize); } else if (v instanceof ViewGroup) setFont((ViewGroup) v, font,textSize); } }}
源码下载: