Android中字体设置Font

本文介绍如何在Android应用中更改默认字体,并使用自定义字体。通过放置.ttf文件在assets/fonts目录下,开发者可以轻松地为TextView和EditText组件设置不同的字体样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.一般使用默认字体,可以使用以下四种安卓系统提供的字体。

     android:typeface="normal"
     android:typeface="sans"
     android:typeface="serif"
     android:typeface="monospace"  

2.如果需要设置其他的字体,则需要先得到字体的 ttf文件,例如 Arial.ttf文件等。
把ttf文件放在assets\fonts目录下。
public class FontTest {
    
    public static void changeFont(ViewGroup root,Activity act){
        Typeface tf = null;
        //创建Typeface对象
        tf = Typeface.createFromAsset(act.getAssets(), "fonts/Arial.ttf");
        for(int i=0;i<root.getChildCount();i++){
            View v = root.getChildAt(i);
            if(v instanceof TextView){
                ((TextView)v).setTypeface(tf);
            }
            else if(v instanceof EditText){
                ((EditText)v).setTypeface(tf);
            }
            else if(v instanceof ViewGroup){
                changeFont((ViewGroup)v, act);
            }
        }
    }
}  

public class MainActivity extends Activity {
    LinearLayout rootview = null;
    TextView world1 = null;
    TextView world2 = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rootview = (LinearLayout)findViewById(R.id.rootview);
        FontTest.changeFont(rootview, this);
//        Typeface tf = null;
//        tf = Typeface.createFromAsset(this.getAssets(), "fonts/Arial.ttf");
//        world1 = (TextView)findViewById(R.id.world1);
//        world2 = (TextView)findViewById(R.id.world2);
//        world2.setTypeface(tf);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值