gpt4 book ai didi

java - 如何将字体设置为 AlertDialog.Builder 的 setMessage 部分?

转载 作者:行者123 更新时间:2023-12-01 16:49:32 24 4
gpt4 key购买 nike

我正在尝试为 AlertDialog.Builder 的消息部分设置字体。以下代码仅适用于标题和按钮。我不知道为什么消息字体不一样?

Java 代码:

AlertDialog.Builder adb = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.MyAlertTheme));
adb.setTitle("My App");
adb.setMessage("Would you like to launch the calendar?"); //Typeface doesn't work for this. Why?

adb.setPositiveButton("Open Calendar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, android.net.Uri.parse("content://com.android.calendar/time/")));
}
})

adb.create();
adb.show();

样式代码

<style name="MyAlertTheme" parent="Theme.AppCompat.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:typeface">monospace</item>
</style>

字体 Java 类

static class DefaultAppFont{
static void setFontForApp(Context context, String typeFaceFieldName, String fontAssetName) {
final Typeface myAppTypeFace = Typeface.createFromAsset(context.getAssets(), fontAssetName);
replaceFont(typeFaceFieldName, myAppTypeFace);
}

private static void replaceFont(String typeFaceFieldName, final Typeface newTypeFace) {
try {
final Field field = Typeface.class.getDeclaredField(typeFaceFieldName);
field.setAccessible(true);
field.set(null, newTypeFace);
}catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}

创建时


DefaultAppFont.setFontForApp(getApplicationContext(), "MONOSPACE", "fonts/myFont.ttf");

谢谢!

这是错误...

AlertDialog.Builder adb = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.MyAlertTheme));
adb.setTitle("My App");
adb.setMessage("Would you like to launch the calendar?");

adb.setPositiveButton("Open Calendar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, android.net.Uri.parse("content://com.android.calendar/time/")));
}
})

AlertDialog dialog = adb.create();
TextView tv = dialog.findViewById(R.id.message);
Typeface tf = ResourcesCompat.getFont(MainActivity.this, R.font.myFont);
tv.setTypeface(tf);
adb.show();
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference

最佳答案

只需使用 android:fontFamily 即可。

关于java - 如何将字体设置为 AlertDialog.Builder 的 setMessage 部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61720785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com