在我的Android应用程序中,单击按钮后会出现一个警告对话框。我想为警报设置自定义字体。我在网上搜索了一些关于这个主题的教程和问题,但它们都不适合我。
如何更改字体?
由于
答案 0 :(得分:71)
要执行此操作,请使用警报构建器来构建警报。然后,您可以从此警报中获取TextView,然后设置警报的字体。
AlertDialog dialog = new AlertDialog.Builder(this).setMessage("Hello world").show();
TextView textView = (TextView) dialog.findViewById(android.R.id.message);
Typeface face=Typeface.createFromAsset(getAssets(),"fonts/FONT");
textView.setTypeface(face);
答案 1 :(得分:17)
上述答案对我没有用。
我使用了以下方法
//You can use this code :
<?php
if (!isset($_GET['email'])) {
echo '<form action="">
Enter Your Email Id:
<input type="text" name="email" />
<input type="submit" value="Reset My Password" />
</form>';
exit();
}
define('DB_USER', '');
define('DB_PASS', '');
define('DB_NAME', '');
$email = $_GET['email'];
function connect()
{
$link = mysql_connect('localhost', DB_USER, DB_PASS);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
}
connect();
$q = "SELECT email FROM users WHERE LCASE(TRIM(email))='" . strtolower(trim($email)) . "'";
$r = mysql_query($q);
$n = mysql_num_rows($r);
if ($n == 0) {
echo "Email id is not registered";
die();
}
在7.1.1上测试
注意:确保在显示// Initializing the alertDialog
AlertDialog alertDialog = new AlertDialog.Builder(QuizActivity.this).create();
alertDialog.setTitle("Warning");
alertDialog.setMessage("Are you sure you want to exit?");
alertDialog.show(); // This should be called before looking up for elements
// Getting the view elements
TextView textView = (TextView) alertDialog.getWindow().findViewById(android.R.id.message);
TextView alertTitle = (TextView) alertDialog.getWindow().findViewById(R.id.alertTitle);
Button button1 = (Button) alertDialog.getWindow().findViewById(android.R.id.button1);
Button button2 = (Button) alertDialog.getWindow().findViewById(android.R.id.button2);
// Setting font
textView.setTypeface(FontHelper.getFont(Fonts.MULI_REGULAR));
alertTitle.setTypeface(FontHelper.getFont(Fonts.MULI_REGULAR));
button1.setTypeface(FontHelper.getFont(Fonts.MULI_BOLD));
button2.setTypeface(FontHelper.getFont(Fonts.MULI_BOLD));
后获取元素。如果没有这个,你将获得dialog
答案 2 :(得分:4)
我知道这是一个老问题,但我将此留给那些仍在寻找解决方案的人。
如果您只想更改文字格式,只需覆盖alertDialogTheme
属性即可更改AlertDialog
的主题。
示例,使用应用主题:
<style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<!-- This will override the Alert Dialog theme -->
<item name="alertDialogTheme">@style/MyAlertDialogTheme</item>
</style>
<style name="MyAlertDialogTheme" parent="@android:style/Theme.Material.Light.Dialog.Alert">
<item name="android:textAppearanceSmall">@style/MyTextAppearanceSmall</item>
<item name="android:textAppearanceMedium">@style/MyTextAppearanceMedium</item>
<item name="android:textAppearanceLarge">@style/MyTextAppearanceLarge</item>
</style>
<style name="MyTextAppearance" parent="TextAppearance.AppCompat">
<item name="android:fontFamily">@font/comic_sans</item>
</style>
(...)
如果我没有弄错,android:textAppearanceSmall
用于邮件,android:textAppearanceMedium
用于标题。但是你可以选择你想要的任何东西并删除其余部分。
另一个选项
不覆盖alertDialogTheme
,是通过构建器构造函数设置样式。示例:AlertDialog.Builder(getActivity(), R.style.MyAlertDialogTheme)
答案 3 :(得分:3)
您可以定义自己要显示的对话框的布局。
这是
的链接Creating a custom dialog in Android
在布局中,您可以使用所需的typeFace定义TextView。您需要下载所需字体的otf文件。将它们放在资产目录中。并将其设置为TextView的TypeFace。以及如何设置TypeFace
这可能会有所帮助
答案 4 :(得分:3)
如果您使用的是Material Components
,则可以通过清除样式来自定义对话框,以满足几乎所有需求。例如,我为对话框创建的自定义样式:
<style name="ThemeOverlay.App.MaterialAlertDialog" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<item name="materialAlertDialogTitleTextStyle"><!--here goes your title text style --></item>
<item name="materialAlertDialogBodyTextStyle"><!--here goes your message text style --></item>
<item name="colorPrimary"><!--here goes your dialog primary color. e.g. button text color, etc.--></item>
<item name="shapeAppearanceOverlay">@style/ShapeAppearance.App.SmallComponent</item> <!-- your custom shape appearance for your dialog. In my case, I am changing corner radius of dialog to rounded 20dp corners-->
<item name="colorSurface">@color/white</item>
<item name="buttonBarPositiveButtonStyle">@style/Widget.App.Button</item> <!-- your custom positive button style-->
<item name="buttonBarNegativeButtonStyle">@style/Widget.App.Button</item> <!-- your custom negtive button style-->
</style>
<style name="ShapeAppearance.App.SmallComponent" parent="ShapeAppearance.MaterialComponents.SmallComponent">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">20dp</item>
</style>
<style name="Widget.App.Button" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="shapeAppearance">@style/ShapeAppearance.App.SmallComponent</item>
<item name="android:textAppearance">@style/Roboto.Bold.Small</item>
<item name="android:textColor">@color/colorAccent</item>
<item name="android:textAllCaps">true</item>
</style>
最后,在创建对话框时,不要忘记设置以下样式:
MaterialAlertDialogBuilder(this, R.style.ThemeOverlay_App_MaterialAlertDialog)
.setMessage("your message")
.show()
答案 5 :(得分:2)
自定义警告对话框标题textview
TextView tv_message = new TextView(this);
Typeface typeface = Typeface.createFromAsset(
getAssets(),
"fonts/OpenSans-Semibold.ttf"
);
// Set the text view layout parameters
tv_message.setLayoutParams(
new
ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
);
// Set message text color
tv_message.setTextColor(Color.RED);
// Set message gravity/text align
tv_message.setGravity(Gravity.START);
// Set message text size
tv_message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
// Set message custom font
tv_message.setTypeface(typeface);
// Set message background color
tv_message.setBackgroundColor(Color.YELLOW);
// Set message text padding
tv_message.setPadding(15, 25, 15, 15);
tv_message.setText("Are you sure?");
tv_message.setTextColor(Color.BLACK);
答案 6 :(得分:1)
您可以使用SpannableString,在其上设置字体并将其返回给AlertDialog.Builder
这是一个辅助函数,它向CharSequence添加字体并返回SpannableString-
private static SpannableString typeface(Typeface typeface, CharSequence chars) {
if (chars == null) {
return null;
}
SpannableString s = new SpannableString(chars);
s.setSpan(new TypefaceSpan(typeface), 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return s;
}
在文本上设置TypeFace的类-
public class TypefaceSpan extends MetricAffectingSpan {
private final Typeface typeface;
public TypefaceSpan(Typeface typeface) {
this.typeface = typeface;
}
@Override
public void updateDrawState(TextPaint tp) {
tp.setTypeface(typeface);
tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
@Override
public void updateMeasureState(TextPaint p) {
p.setTypeface(typeface);
p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
}
在创建对话框时,您可以像这样用SpannableString替换字符串-
public static Dialog createDialog(Context c, String title, String message, String pButton, String nButton, AlertCallback callback) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setMessage(typeface(Fonts.Regular, message));
builder.setTitle(typeface(Fonts.Bold, title));
builder.setPositiveButton(typeface(Fonts.Bold, pButton),callback::onPositiveButtonClick);
builder.setNegativeButton(typeface(Fonts.Bold, nButton),callback::onNegativeButtonClick);
AlertDialog dialog = builder.create();
return builder.create();
}
我建议将字体加载到缓存中,而不要多次调用createFromAsset。 希望这会有所帮助!
答案 7 :(得分:0)
我有一个包含项目列表的警报对话框,因此我必须结合几个答案并对其进行一些简化,这是警报对话框本身的代码:
val dialog = AlertDialog.Builder(this, R.style.MyAlertDialogTheme).setTitle(R.string.sort_by)
.setSingleChoiceItems(modelList, selectedSortPosition) { _, position -> selectedSortPosition = position }
.setPositiveButton(R.string.ok) { _, _ -> }
.setNegativeButton(R.string.cancel) { _, _ -> }.create()
dialog.show()
setFontsForDialog(dialog)
在这里,我使用了Danilo的答案中的样式,但是为此添加了设置的主题颜色:
<style name="MyAlertDialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog.Alert">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:textAppearanceSmall">@style/MyTextAppearanceSmall</item>
<item name="android:textAppearanceMedium">@style/MyTextAppearanceMedium</item>
<item name="android:textAppearanceLarge">@style/MyTextAppearanceLarge</item>
</style>
并且由于它仅更改列表项的字体,因此我添加了此方法,并且由于我打算在应用程序中多次使用它,因此我为活动本身创建了扩展方法:
private fun Activity.setFontsForDialog(dialog: AlertDialog) {
val font = ResourcesCompat.getFont(this, R.font.theme_bold_pn)
dialog.findViewById<TextView>(android.R.id.message)?.typeface = font
dialog.findViewById<TextView>(android.R.id.button1)?.typeface = font
dialog.findViewById<TextView>(android.R.id.button2)?.typeface = font
}
答案 8 :(得分:0)
我为此目的为AlertDialog创建了扩展方法-
(从androidx.appcompat:appcompat:1.1.0开始有效)
fun AlertDialog.setTypefaceInDialog(context: Context) {
val regularFont = ResourcesCompat.getFont(context, R.font.regular_font)
val boldFont = ResourcesCompat.getFont(context, R.font.medium_font)
findViewById<TextView>(androidx.appcompat.R.id.alertTitle)?.typeface = boldFont
findViewById<TextView>(android.R.id.message)?.typeface = regularFont
getButton(AlertDialog.BUTTON_POSITIVE).typeface = boldFont
getButton(AlertDialog.BUTTON_NEGATIVE).typeface = boldFont
}