Android Studio中的按钮如何更改字体族?

5
我想要改变按钮的字体族。我尝试了使用以下代码来更改它:
Button txt = (Button)findViewById(R.id.button1);
Typeface font = Typeface.createFromAsset(getAssets(), "sfont.ttf");
txt.setTypeface(font);

但是我遇到了一个错误,如果不理会它,每次应用程序都会崩溃。
这是布局XML代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical"
>

<TextView

    android:text="@string/enter"
    android:textColor="#000"
    android:textSize="16dp"
    android:textAlignment="center"
    android:id="@+id/**button1**"text1
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:padding="20dp" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/**text1**" button1
    android:padding="30dp"
    android:layout_gravity="center"
    android:text="@string/entenbut"
    />

问题已解决,XML代码存在问题。感谢大家的帮助 :)


1
你介意和我们分享一下异常的堆栈跟踪吗? - Blackbelt
抱歉,我该如何获取异常的堆栈跟踪?这是我的第一个应用程序 :) - Ayham Najem
检查 logcat 的内容 - Blackbelt
为什么要将 AppCompatTextView 强制转换成 Button - Blackbelt
你介意发布一下你正在使用的布局吗? - Blackbelt
显示剩余4条评论
2个回答

4
在您的“src”文件夹中创建一个名为“Assets”的文件夹(如果您使用Android Studio),并使用以下命令:
Typeface tfFutura = Typeface.createFromAsset(getAssets(), "sfont.ttf");

一个观察:请查看您的文件是否包含“TTF”或“ttf”。我曾经因此遇到过问题。

没有问题,我可以使用相同的代码编辑TextView的字体族,但无法编辑按钮。 - Ayham Najem
请展示堆栈跟踪日志。当错误发生时,您可以在logcat中获取它。 - Siloé Bezerra Bispo
请尝试查看以下链接:https://dev59.com/HXPYa4cB1Zd3GeqPlJ02 或者 https://dev59.com/B-o6XIcBkEYKwwoYPSDf - Siloé Bezerra Bispo
点击 Build > Clean Project。 - Siloé Bezerra Bispo
你的按钮使用了R.id.button1,但是在xml中你的Button使用了"@+id/text1"。 - Siloé Bezerra Bispo
显示剩余3条评论

1
在Android Studio中,没有“src”目录,但有“res”目录。 要创建资产目录,请首先右键单击“app”,然后: 新建 -> 文件夹 -> 资产文件夹。完成后,将字体复制到此目录中。 点击此处获取更多信息

1
谢谢!这篇文章正是我所需要的。 - Hashim Akhtar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接