I know we can change edit text font by using Typeface. But what about errors we set for edit text?
Look at codes below:
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/ATaha.ttf");
private EditText mPasswordView;
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setTypeface(font);
With this code I could only change edit text font but when I set error like this:
mPasswordView.setError(getString(R.string.error_field_required));
The error notification font is android default font and didn't change by using type face. How can I change that?
You can use a SpannableString to set the font:
SpannableString s = new SpannableString(errorString);
s.setSpan(new TypefaceSpan(font), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mPasswordView.setError(s);
A custom Span class that has a specific Typeface set:
public class TypefaceSpan extends MetricAffectingSpan {
private Typeface mTypeface;
public TypefaceSpan(Typeface typeface) {
mTypeface = typeface;
}
#Override
public void updateMeasureState(TextPaint p) {
p.setTypeface(mTypeface);
p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
#Override
public void updateDrawState(TextPaint tp) {
tp.setTypeface(mTypeface);
tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
}
Since you can't directly set a Typeface for error text, you can achieve it by setting an HTML string as a text inside it.
You can see HTML Tags supported by a TextView in The CommonsBlog
We have face attribute for font, which means you can change the font-family.
mPasswordView.setError(Html.fromHtml("<font face='MONOSPACE'>Error font is MONOSPACE</font>"));
By setting spannable string in error message or extend EditText and overrite your own error draw mechanism.
Related
A TextView is displayed in one activity and the user goes to another activity to edit the properties of the text such as color, size, bold, italics, and underlined. When the user chooses to make the text bold, italic, or bold_italic it works. If the user unselects the checkbox the TextView does not return to normal. It can shift between the styles (ie if I check bold, then uncheck bold and check italic the TextView will be italic, not bold) but it cannot have a normal TypeFace.
I've searched around and everything I've found says that using the setTypeface method with Typeface.NORMAL should work but it is not working.
I would appreciate some help in solving this. The relevant code is below. Thank you!
TextView mDisplayMessage = (TextView) findViewById(R.id.message);
mDisplayMessage.setTypeface(mDisplayMessage.getTypeface(), Typeface.NORMAL);
//TODO: Cannot return all the way back to normal. Remains bold/italic/bold_italic
if (mIsBold && mIsItalic) mDisplayMessage.setTypeface(mDisplayMessage.getTypeface(), Typeface.BOLD_ITALIC);
else if (mIsBold) mDisplayMessage.setTypeface(mDisplayMessage.getTypeface(), Typeface.BOLD);
else if (mIsItalic) mDisplayMessage.setTypeface(mDisplayMessage.getTypeface(), Typeface.ITALIC);
else mDisplayMessage.setTypeface(mDisplayMessage.getTypeface(), Typeface.NORMAL);
if (mIsUnderlined) {
mDisplayMessage.setPaintFlags(mDisplayMessage.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
} else {
mDisplayMessage.setPaintFlags(0);
}
If you didn't care about font family you can use
mDisplayMessage.setTypeface(Typeface.DEFAULT);
Because Typeface.DEFAULT change the font family(serif, sans-serif, monospace), but the below can keep the same font family with style changed.
Typeface typeface = mDisplayMessage.getTypeface();
int style = Typeface.NORMAL;
if(mIsBold && mIsItalic) {
style = Typeface.BOLD_ITALIC;
} else if(mIsBold) {
style = Typeface.BOLD;
} else if(mIsItalic) {
style = Typeface.ITALIC;
}
Typeface newTypeface = Typeface.create(typeface, style);
mDisplayMessage.setTypeface(newTypeface);
Try this,
mDisplayMessage.setTypeface(Typeface.DEFAULT);
OR
mDisplayMessage.setTypeface(null, Typeface.NORMAL);
In my project, I need to toggle TextView style to Normal and Bold. Here is the code:
mTitleTextView.setTypeface(mTitleTextView.getTypeface(), letterItem.isRead() ? Typeface.NORMAL : Typeface.BOLD);
This works good when TextView is not bold. But when current state is bold, it doesn't return to normal state.
mTitleTextView.setTypeface(null, letterItem.isRead() ? Typeface.NORMAL : Typeface.BOLD);
Above line fixes the problem, but I have used custom font and passing null for current typeface removes the font.
After tying for a while this works for me :
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.invalidate();
if(isCliked){
isCliked = false;
Typeface face=Typeface.createFromAsset(getAssets(), "test.ttf");
textView.setTypeface(face,Typeface.NORMAL);
}
else{
Typeface face=Typeface.createFromAsset(getAssets(), "test.ttf");
textView.setTypeface(face, Typeface.BOLD);
isCliked = true;
}
Log.i("MainActivity", "onClick: "+isCliked);
}
});
the typeface will remain the same, and change only bold and normal
I have been trying to set custom font to the android.support.v7.widget.SearchView query hint and the text entered in the View.I did try setting the font dynamically from the assests to the searchView by creating a TypeFace object, but the problem occurs that "SearchView doesn't contain a setTypeface(Typeface tf) method." I did try for a custom SearchView class but couldn't find one.
private void setFont(String font1, String font2, String font3)
{
Typeface tf = null;
tf = UiUtil.changeFont(MainActivity.this, font1);
btn1.setTypeface(tf);
tf = UiUtil.changeFont(MainActivity.this, font2);
btn2.setTypeface(tf);
tf = UiUtil.changeFont(MainActivity.this, font3);
btn3.setTypeface(tf);
tf = UiUtil.changeFont(MainActivity.this, font3);
// no set typeface method..
}
The workaround here is to first get the searchView's textView and then change the typeface for the textView instead:
TextView searchText = (TextView)
searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(),"fonts/myFont.ttf");
searchText.setTypeface(myCustomFont);
Or, if you're not using appcompatv7:
int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView searchText = (TextView) searchView.findViewById(id);
then set the typeface as usual.
To change the font family in searchview programmatically from xml font folder:
Typeface tf = ResourcesCompat.getFont(dis,R.font.montserrat_regular);
TextView searchText = (TextView)search_view.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchText.setTypeface(tf);
For Kotlin and Androidx
val face: Typeface = Typeface.createFromAsset(context?.assets, "font.otf")
val searchText = searchView.findViewById<View>(androidx.appcompat.R.id.search_src_text) as TextView
searchText.typeface = face
Thanks to all the previous answers, I found my best solution witch I hope that you find it the cleanest answer, too.
This is working for SearchView class inside the package android.widget
First, create an extension like below:
import android.graphics.Typeface
import android.widget.SearchView
import android.widget.TextView
fun SearchView.setTypeFace(typeface: Typeface?) {
val id = context.resources.getIdentifier("android:id/search_src_text", null, null)
val searchText = searchView.findViewById(id) as TextView
searchText.typeface = typeface
}
Then use this extension wherever you like:
val typeface = ResourcesCompat.getFont(requireContext(), R.font.sans)
searchView.setTypeFace(typeface)
You may want to get typeface from assets or other ways. but the rest is the same.
If anyone looking to implement the same in xml
Try the solution mentioned this answer able to customise
{textSize, fontFamily, textColor, hideBottomLine} in SearchView - https://stackoverflow.com/a/73997430/3020859
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);
My android application will use Chinese. The regular font is OK, but the italic font and bold font does not work.
So which font files should I use for Chinese italic and bold font?
I assume you are using TextView to show Chinese words.
If you want the whatever words in TextView to be bold or italic, it would be easy.
Just use
testView.getPaint().setFakeBoldText(true);
to make all words bold.
For italic, use:
testView.getPaint().setTextSkewX(-0.25f);
However, if you only want some words to be bold or italic. Normally you can set StyleSpan on specific range of your Spannablebut it is not work on Chinese word.
Therefore, I suggest you create a class extends StyleSpan
public class ChineseStyleSpan extends StyleSpan{
public ChineseStyleSpan(int src) {
super(src);
}
public ChineseStyleSpan(Parcel src) {
super(src);
}
#Override
public void updateDrawState(TextPaint ds) {
newApply(ds, this.getStyle());
}
#Override
public void updateMeasureState(TextPaint paint) {
newApply(paint, this.getStyle());
}
private static void newApply(Paint paint, int style){
int oldStyle;
Typeface old = paint.getTypeface();
if(old == null)oldStyle =0;
else oldStyle = old.getStyle();
int want = oldStyle | style;
Typeface tf;
if(old == null)tf = Typeface.defaultFromStyle(want);
else tf = Typeface.create(old, want);
int fake = want & ~tf.getStyle();
if ((want & Typeface.BOLD) != 0)paint.setFakeBoldText(true);
if ((want & Typeface.ITALIC) != 0)paint.setTextSkewX(-0.25f);
//The only two lines to be changed, the normal StyleSpan will set you paint to use FakeBold when you want Bold Style but the Typeface return say it don't support it.
//However, Chinese words in Android are not bold EVEN THOUGH the typeface return it can bold, so the Chinese with StyleSpan(Bold Style) do not bold at all.
//This Custom Class therefore set the paint FakeBold no matter typeface return it can support bold or not.
//Italic words would be the same
paint.setTypeface(tf);
}
}
Set this span to your Chinese words and I should be work.
Be aware to check it is only set on Chinese words only. I have not test on it but I can imagine that set fakebold on a bold English characters would be very ugly.
I'd suggest you don't use bold and italic fonts when displaying chinese text.
Bold is likely to distort the text and italic will only artificially skew the text.