Change title font of Alert Dialog box - android

I want to change the font of the title of Alert Dialog box.
Can anybody tell how can I do it?

I found a simple solution..
At first I was setting the title of my alert box by
builder.setTitle("My Title");
So I was not able to change the font of it..
Then what worked for me is..
I created a simple TextView :
TextView tv2;
And set all properties of TextView which I wanted...
And then I replaced my
builder.setTitle("My Title");
line with
builder.setCustomTitle(tv2);
and now I can change Title Color, Font Etc By Changing tv2's Properties..

No answers provide a way to change the title typeface of an AlertDialog. Here is what I have done:
Create the below class:
public static 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);
}
}
Add the following utility method:
/**
* <p>Return spannable string with applied typeface in certain style</p>
*
* http://stackoverflow.com/questions/8607707/how-to-set-a-custom-font-in-the-actionbar-title
*
* #param typeface
* The typeface to set to the {#link SpannableString}
* #param string
* the string to place in the span
* #return SpannableString that can be used in TextView.setText() method
*/
public static SpannableString typeface(Typeface typeface, CharSequence string) {
SpannableString s = new SpannableString(string);
s.setSpan(new TypefaceSpan(typeface), 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return s;
}
Finally, set the typeface when creating your AlertDialog:
Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/your_font.ttf");
new AlertDialog.Builder(getActivity())
.setTitle(FontUtils.typeface(typeface, "The title"))
/* .. */
.create();

Just use the following line to get an identifier to the dialog's title:
int dialogTitle = mCtnx.getResources().getIdentifier( "alertTitle", "id", "android" );
use this one for android.support.v7.app.AlertDialog
TextView title= (TextView)alertDialog.findViewById(R.id.alertTitle);

You have to inflate or customize and create a style and apply to AlertDialog
Heres how you inflate a layout and apply it to AlertDialog
LayoutInflater li = LayoutInflater.from(ctx);
View view = li.inflate(R.layout.formatted_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setTitle("Formatted");
builder.setView(view);
define all the formatting and styles required in the layout you specified.
You can access specific textview defined in the layout using inflated View i.e.
LayoutInflater li = LayoutInflater.from(ctx);
View view = li.inflate(R.layout.formatted_dialog, null);
TextView label=(TextView)view.findViewById(R.id.i_am_from_formatted_layout_lable);
Sample layout saved as res/layout/link.xml:
In your onCreate() or where or whenever you want to call AlertDialog
LayoutInflater li = LayoutInflater.from(this);
View view = li.inflate(R.layout.link, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Formatted");
builder.setView(view).create().show();
TextView text=(TextView) findViewById(R.id.text);
replace this with context object if you are calling from some other method.

Do like this :
Dialog dialog = new Dialog(ActivityName.this);
dialog.setContentView(R.layout.dialog_name);
dialog.setCancelable(true);
dialog.findViewById(R.id.text).setTypeface(Typeface.createFromAsset(getAssets(), "font.ttf"));
Have your font.ttf file in the assets folder and use it like above

Instead of setting the text of the alertdialog, you should set a custom view form your layouts. And before you do so, modify your view's font.
try this example
TextView content = new TextView(this);
content.setText("on another font");
content.setTypeface(Typeface.SANS_SERIF);
//Use the first example, if your using a xml generated view
AlertDialog.Builder myalert = new AlertDialog.Builder(this);
myalert.setTitle("Your title");
myalert.setView(content);
myalert.setNeutralButton("Close dialog", null);
myalert.setCancelable(true);
myalert.show();
code for xml...replace your font in the xml
<TextView
android:id="#+id/yourid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="your content" />

Include this layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello_World"
android:textColorLink="#FF00FF"
/>
</LinearLayout>
Then use it inside Ur Activity
Dialog dialog = new Dialog(ActivityName.this);
dialog.setContentView(R.layout.dialog_name);
dialog.setCancelable(true);
dialog.findViewById(R.id.text).setTypeface(Typeface.createFromAsset(getAssets(), "font.ttf"));
Another Way and this

You can try Spannable as well.
SpannableString s = new SpannableString("My App");
s.setSpan(new TypefaceSpan(this, "font.otf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
s.setSpan(new RelativeSizeSpan(1.3f), 0,s.length(), 0);
builder.setTitle(s)

You can change appearence of AlertDialog by following this block of code:
AlertDialog dialog = new AlertDialog.Builder(this).setMessage("Message").show();
TextView textView = (TextView) dialog.findViewById(android.R.id.message);
textView.setTextSize(10);//to change font size
//to change font family
Typeface face = Typeface.createFromAsset(getAssets(),"font/fontFileName.ttf");
textView.setTypeface(face);
Put font file in assets folder. In my case I created a subdirectory called font.
And you can also check for this Question which have an accepted answer.

You can add this
TextView textViewt = (TextView) alertDialog.findViewById(android.R.id.title);
textViewt.setTypeface(your font typeface);
after the line
alertDialog.show();

There is an easy way to set a new custom view to dialog's title. We can define every custom view such as TextView and add it some custom properties and at last set it to dialog's title, such as below:
AlertDialog.Builder builder = new AlertDialog.Builder(OrderItemsActivity.this);
TextView title_of_dialog = new TextView(getApplicationContext());
title_of_dialog.setHeight(50);
title_of_dialog.setBackgroundColor(Color.RED);
title_of_dialog.setText("Custom title");
title_of_dialog.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
title_of_dialog.setTextColor(Color.WHITE);
title_of_dialog.setGravity(Gravity.CENTER);
builder.setCustomTitle(title_of_dialog);
builder.create().show();
Here, I define a dynamic TextView and set some properties to it. Finally, I set it to dialog's title using "setCustomTitle()" function.

Use this method from support library 26.
ResourcesCompat.getFont(context, R.font.<YOUR_FONT>);
Read For more: Source

Try setting theme for the dialog. Change the typeface attribute like this :
<style name="CustomDialog" parent="android:Theme.Dialog">
<item name="android:typeface">serif</item>
</style>
Though this changes Fonts of all the textviews within the dialog.
so make sure TextViews are set to proper typeface

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);

Related

How do I set a custom font in an AlertDialog using Support Library 26

I am using revision 26.0.1 of the Android Support Library to set custom fonts in my app. In my app's theme, I added:
<item name="android:fontFamily">#font/my_font</item>
It worked like a charm, converting the text in my whole app to my custom font. EXCEPT for my dialogs - specifically their titles, messages, and also their NumberPickers. In those places, fonts were not updated. (Radio buttons and checkboxes worked; so did the yes/no buttons)
Is there something I'm forgetting to add to my themes or styles? Or is this simply not supported yet by the support library?
A little more detail: I am using AppCompatDialogFragment to implement all my dialogs. In their onCreateDialog() methods, I create a dialog using AlertDialog.Builder then return it.
Thanks for the help!
Thank you everybody who answered, but unfortunately none of those solutions worked for me. I hope they will work for someone else.
I've concluded that this is a bug in the support library, and hopefully Google will fix. In the meantime, I developed this hacky workaround:
public static void applyCustomFontToDialog(Context context, Dialog dialog) {
Typeface font = ResourcesCompat.getFont(context, R.font.my_font);
if (font != null) {
TextView titleView = dialog.findViewById(android.support.v7.appcompat.R.id.alertTitle);
TextView messageView = dialog.findViewById(android.R.id.message);
if (titleView != null) titleView.setTypeface(font, Typeface.BOLD);
if (messageView != null) messageView.setTypeface(font);
}
}
This works by scanning the dialog's view tree for the title and message views by the IDs that the support library gives them. If the support library were to change these IDs, this would no longer work (which is why it's hacky). Hopefully Google fixes this issue and I won't need to do this anymore.
I've found a way that only requires a one-line change to Java code every time you create an AlertDialog.
Step 1
Create a custom, reusable layout containing a TextView with the correct font set. Call it alert_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/SomeStyleWithDesiredFont"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/spacing_2x" />
Step 2
Create a reusable helper function somewhere that will inflate this layout and set the text to your desired string
public static TextView createMessageView(String message, Context context) {
TextView messageView = (TextView) LayoutInflater.from(context).inflate(R.layout.alert_dialog, null, false);
messageView.setText(message);
return messageView;
}
Step 3
In every AlertDialog.Builder chain in your code, replace this line:
.setMessage(messageString)
with this line:
.setView(createMessageView(messageString, context))
(Note that the same approach should work for the title TextView. You can apply a custom view for the title by calling setCustomTitle() in your builder)
You should use a ContextThemeWrapper when creating the dialog builder. Like this
ContextThemeWrapper wrappedContext = new ContextThemeWrapper(context, R.style.mystyle);
AlertDialog.Builder builder = new AlertDialog.Builder(wrappedContext);
If you are supporting only SDK 11 and above, you may want to use
ContextThemeWrapper wrappedContext = new ContextThemeWrapper(context, R.style.mystyle);
AlertDialog.Builder builder = new AlertDialog.Builder(wrappedContext, R.style.mystyle);
Perhaps not the case here, I had a similar issue and found that fontFamily would not be impimented using the AsyncLayoutInflater. This is also the case if the AlertDialog is nested inside the AsyncLayoutInflater. I had to convert to the conventional layout inflator in order for the custom font to show. For example,
This did not show fontFamily called from TextView XML.
AsyncLayoutInflater inflater =new AsyncLayoutInflater(activity);
inflater.inflate(R.layout.dialog, null, new AsyncLayoutInflater.OnInflateFinishedListener() {
#Override
public void onInflateFinished(#NonNull View view, int resid, ViewGroup parent) {
final TextView tv = view.findViewById(R.id.textview);
tv.setText("Text with custom fontFamily called in XML, but won't work");
}
});
This did show fontFamily called from TextView XML.
final ViewGroup nullParent = null;
final View view = activity.getLayoutInflater().inflate(R.layout.dialog, nullParent);
final TextView tv= view.findViewById(R.id.textview);
tv.setText("Text with custom fontFamily called in XML, and will work");
you can inflate a custom layout in your dialog like this:
final android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(context,
R.style.LimitAlertDialogStyle);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View alertLayout = layoutInflater.inflate(R.layout.date_layout, null);
TextView tv= (TextView) alertLayout.findViewById(R.id.tv);
Typeface fc=Typeface.createFromAsset(getAssets(),"fonts/FONT");
tv.setTypeface(fc);
You can use custom Alert Dialog and set the font using Typeface. Have a look at below code snippet.
AlertDialog dg = new AlertDialog.Builder(this).setMessage("Your Message").show();
TextView tv = (TextView) dg.findViewById(android.R.id.message); // Your TextView of custom Alert Dialog
Typeface fc=Typeface.createFromAsset(getAssets(),"fonts/FONT"); // This is your font file name.
tv.setTypeface(fc);

How to set custom font to android toolbar's subtitle?

i want to get the subtitle´s textview in an android's toolbar to change it's font. Actually i'm doing it with the title, getting it on this way:
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView) f.get(toolbar);
I've tried with the same code but trying to get "mSubtitleTextView" but that's not the solution.
Thanks!!
You can get the subtitle TextView like this:
View subTitleView = toolbar.getChildAt(1);
If you don't add any views to the toolbar, his default structure is:
[0] - (TextView) title
[1] - (TextView) subtitle
[2] - (ActionMenuView) menu
Hope it helps!
Definitely not the best way, but in a pinch this will work. You will have to figure out a way to implement myTypefaceSpan though; I'm using Calligraphy so it ties together decently for me.
CalligraphyTypefaceSpan myTypefaceSpan = new CalligraphyTypefaceSpan(
TypefaceUtils.load(this.getAssets(), "fonts/custom_font.ttf"));
public static void setToolbarSubtitle(String subtitle, Context context) {
SpannableStringBuilder sBuilder = new SpannableStringBuilder();
sBuilder.append(subtitle);
sBuilder.setSpan(MainActivity.myTypefaceSpan, 0, sBuilder.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
((MainActivity)context).getSupportActionBar().setSubtitle(sBuilder);
}

Android : Crouton lib and custom font

I use custom fonts in my app so i want a custom font for Crouton. I 've tried to do it with setTextAppearance, it doesn't work.
<?xml version="1.0" encoding="utf-8"?>
<com.ecab.ui.custom.TextViewCustomFont
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.crouton"
android:id="#+id/crouton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ban_confirmation"
android:gravity="center"
android:text="TEST"
android:textColor="#android:color/white"
custom:typeface="gothamBold" />
In Style class :
INFOCUSTOM = new Builder().setDuration(3000).setTextAppearance(R.id.crouton).build();
Then, I've tried to do it by changing setTypeface() with my font, it doesn't work.
In Crouton class :
private TextView initializeTextView(final Resources resources) {
TextView text = new TextView(this.activity);
text.setId(TEXT_ID);
text.setText(this.text);
text.setTypeface(MyFonts.getGothamBookBold(this.activity));
Log.d(Constants.D_TAG, "chaneg the typeFace");
text.setGravity(this.style.gravity);
// set the text color if set
if (this.style.textColorResourceId != 0) {
text.setTextColor(resources.getColor(this.style.textColorResourceId));
}
// Set the text size. If the user has set a text size and text
// appearance, the text size in the text appearance
// will override this.
if (this.style.textSize != 0) {
text.setTextSize(TypedValue.COMPLEX_UNIT_SP, this.style.textSize);
}
// Setup the shadow if requested
if (this.style.textShadowColorResId != 0) {
initializeTextViewShadow(resources, text);
}
// Set the text appearance
if (this.style.textAppearanceResId != 0) {
text.setTextAppearance(this.activity, this.style.textAppearanceResId);
}
return text;
}
What can i do to have a custom Font ?
ps : library version ==> 1.7
Okay, I found the problem !
It works with the second solution by changing the Typeface. I had just forget to remove the
setTextAppearance(R.id.crouton)
in the Style class. So my custom style is like this :
INFOCUSTOM = new Builder().setDuration(3000).setBackgroundDrawable(R.drawable.ban_confirmation).setHeight(LayoutParams.WRAP_CONTENT)
.build();
One problem resolves, another arrives :) ! With the background drawable, the text is not vertically center
You can a custom Style that uses the resourceId of your text
appearance via Style.Builder.setTextAppearance(...).
This takes a reference from your styles.xml and uses it within the
internal TextView of the Crouton.
Then you can call Crouton.makeText or Crouton.showText with your
custom Style.
Source
How does MyFonts.getGothamBookBold() look like?
This however should work:
private TextView initializeTextView(final Resources resources) {
TextView text = new TextView(this.activity);
text.setId(TEXT_ID);
text.setText(this.text);
Typeface myTypeFace = Typeface.createFromAsset(this.activity.getAssets(), "gothamBold.ttf");
text.setTypeface(myTypeFace);
text.setGravity(this.style.gravity);
// set the text color if set
if (this.style.textColorResourceId != 0) {
text.setTextColor(resources.getColor(this.style.textColorResourceId));
}

How can I get reference on TextView from XML layout in AlertDialog?

I have a curious problem with getting reference on TextView, SeekBar and other widgets. My AlertDialog looks like this:
public class LineDialog extends AlertDialog {
private static SeekBar seekBar1, seekBar2, seekBar3;
private static TextView textView1, textview2, textView3;
protected LineDialog(final Context context, final DrawView drawView) {
super(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.line_dialog, null);
setView(dialogLayout);
setTitle("Line properties");
textView1 = (TextView) findViewById(R.id.textView1); // TODO Code crash here :(
setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
seekBar1 = (SeekBar) findViewById(R.id.seek1);
// some other code...
}
});
}
When I want get reference in Line where is
textView1 = (TextView) findViewById(R.id.textView1);
Logcat send me an Error
requestFeature() must be called before adding content
But when I get reference in onClick() method in LineDiealog(AlertDialog) everything works fine. Unfortunately this is too late, because I need this reference before LineDialog.show() is called...
You almost had it there in your original code. You saved the View returned by LayoutInflater, so that's the one you should use when calling findViewById() so it must be dialogLayout.findViewById(...). I was having the same issue myself and works like charm now.
Here is an example of the custom AlertDialogbox and How to implement a custom AlertDialog View
you can see how to add the view to the alertdialogbox.
You must either reference your textView by LinearLayout or by android:id in the xml file.
LinearLayout example:
LinearLayout mainLinear = new LinearLayout(this);
mainLinear.addView(textBox);
the add text to the box:
textBox.addText("This is the text to add to the text box");
xml reference (you must create the text box in xml first!!!!):
TextView text1=(TextView) findViewById(R.id.NAME);
text1.setText("Hello please pick an option below");
The NAME portion must be replaced with the android:id name in the .xml file

Custom font in android project

I am trying to assign a different font to my project.
I want the new font is valid for the entire project, but all I find is to change the font to a textview
Typeface font1 = Typeface.createFromAsset(getAssets(), "fonts/RockFont.ttf");
TextView customText1 = (TextView)findViewById(R.id.text1);
customText1.setTypeface(font1);
customText1.setTextSize(40.f);
customText1.setText("Hello! This is a custom font...");
There any way to default to the entire project a custom font?
Best regard
Not exactly what you asked for, but building on the comment above there are ways to make using a custom font with default controls easier.
This shows how to extend TextView and use a custom attribute so the TextView supports a custom font.
Custom fonts and XML layouts (Android)
What I do is create a support class and instantiate it from my activity and pass through all the views I wish to style.
public class textfactory{
private TextView tv;
private Button b;
private RadioButton rb;
private TypeFace font;
/**
* fetch font resource
*/
public textfactory(Context context){
this.font = Typeface.createFromAsset(context.getAssets(), 'customfont.ttf');
}
/**
* pass in all the views you wish to apply font to
*/
public void style(View... views){
for(View v : views){
if(v instance of TextView)
{
tv = (TextView)v;
tv.setTypeface(this.font);
}
else if(v instance of Button)
{
b = (Button)v;
b.setTypeface(this.font);
}
else if(v instance of RadioButton)
{
rb = (RadioButton)v;
rb.setTypeface(this.font);
}
//add as many view conditionals as required
}
}
}

Categories

Resources