You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中用Java实现点击按钮切换TextView字体

实现Android自定义字体切换按钮(Java)

步骤1:放置字体文件

把你的4个字体文件(Simonetta_regular.ttf、Simonetta_black.ttf、Simonetta_black_italic.ttf、Simonetta_italic.ttf)放到项目的 assets/fonts/ 目录下,没有fonts文件夹就手动创建。

步骤2:初始化字体列表与控件

在Activity类中定义成员变量存储字体列表、当前字体索引,以及TextView和Button的引用,然后在onCreate方法完成初始化:

import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ArrayList<Typeface> fontList;
    private int currentFontIndex = 0;
    private TextView targetTextView;
    private Button switchFontBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 绑定布局控件
        targetTextView = findViewById(R.id.your_textview_id);
        switchFontBtn = findViewById(R.id.your_button_id);

        // 填充字体列表
        fontList = new ArrayList<>();
        fontList.add(Typeface.createFromAsset(getAssets(), "fonts/Simonetta_regular.ttf"));
        fontList.add(Typeface.createFromAsset(getAssets(), "fonts/Simonetta_black.ttf"));
        fontList.add(Typeface.createFromAsset(getAssets(), "fonts/Simonetta_black_italic.ttf"));
        fontList.add(Typeface.createFromAsset(getAssets(), "fonts/Simonetta_italic.ttf"));

        // 设置初始显示字体
        targetTextView.setTypeface(fontList.get(currentFontIndex));
    }
}

步骤3:实现按钮点击切换逻辑

给按钮添加点击监听,每次点击更新字体索引,循环切换字体(到最后一个后回到第一个):

// 在onCreate方法内添加按钮点击事件
switchFontBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // 循环更新索引
        currentFontIndex = (currentFontIndex + 1) % fontList.size();
        // 应用新字体
        targetTextView.setTypeface(fontList.get(currentFontIndex));
    }
});

额外提示

  • 确保字体文件名和代码中的路径完全一致,Android系统对文件名大小写敏感。
  • 如果需要保存字体选择状态(比如重启APP后保留上次选中的字体),可以用SharedPreferences存储currentFontIndex的值,在onCreate时读取恢复。

内容的提问来源于stack exchange,提问作者muhammetbalikci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:05:32