I am trying to use Custom Typeface Span in my application but it doesn't working. Here is my code
Typeface font3 = Typeface.createFromAsset(context.getAssets(), "fontawesome-webfont.ttf");
SpannableStringBuilder SS = new SpannableStringBuilder("");
SS.setSpan(new CustomTypefaceSpan("", font3), 0, 8,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
textView.setText(SS);
Here I am trying to use Font-Awesome in Custom Typeface Span.
You can create a Custom TypefaceSpan and then you can use it anywhere to apply font style in any place.
Create a class TypefaceSpan as mentioned below.
public class TypefaceSpan extends MetricAffectingSpan {
/** An <code>LruCache</code> for previously loaded typefaces. */
private static LruCache<String, Typeface> sTypefaceCache =
new LruCache<String, Typeface>(12);
private Typeface mTypeface;
/**
* Load the {#link Typeface} and apply to a {#link android.text.Spannable}.
*/
public TypefaceSpan(Context context, String typefaceName) {
mTypeface = sTypefaceCache.get(typefaceName);
if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getApplicationContext()
.getAssets(), typefaceName);//String.format("fonts/%s", typefaceName));
// Cache the loaded Typeface
sTypefaceCache.put(typefaceName, mTypeface);
}
}
#Override
public void updateMeasureState(TextPaint p) {
p.setTypeface(mTypeface);
// Note: This flag is required for proper typeface rendering
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);
}
and then you can use this class for applying font styles.
Example--
actionBar=getSupportActionBar();
SpannableString s = new SpannableString("Hostel-16");
s.setSpan(new com.example.suraj.hostel16.TypefaceSpan(getApplicationContext(),"georgia.ttf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
actionBar.setTitle(s);
Related
This question already has answers here:
TextView with different fonts and styles?
(3 answers)
Closed 5 years ago.
Assume my title is "Nearby - Friends" I want to show that as "Nearby-
Friends"
How can I achieve it.
I tired a lot but I can't achieve that.
HERE is code that I use, I use Typeface
TextView text = (TextView) tab.getCustomView();
String subTitle = text.getText().toString().trim();
text.setTextColor(getResources().getColor(R.color.white));
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf");
text.setTypeface(face);
TextView title = new TextView(getApplicationContext());
title.setText("Nearby - ");
title.setTypeface(face);
if (subTitle.equals("NEAR BY")) {
subTitle = "People";
} else if (subTitle.equals("FRIENDS")) {
subTitle = "Friends";
} else if (subTitle.equals("FAMILY")) {
subTitle = "Family";
}
toolbar.setTitle(title.getText().toString() + subTitle);
Try This
Let say myToolBar is your toolbar layout in xml.
Toolbar toolBar = (Toolbar) findViewById(R.id.myToolbar);
setSupportActionBar(toolBar);
Then Add Below code
String title = "<b>Near by-</b>Friends"
getSupportActionBar().setTitle(Html.fromHtml(title));
You can use SpannableString to set different font style for single string sentence in TextView or other text enabled component
String strMessage="Nearby- Friends";
Spannable spannable = new SpannableString(strMessage);
//"Nearby-" bold font
spannable.setSpan(getTextAppearanceSpan(ContextCompat.getColor(mContext, android.R.color.BLACK),Typeface.BOLD), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);
//"Friends" normal font
spannable.setSpan(getTextAppearanceSpan(ContextCompat.getColor(mContext, android.R.color.BLACK),Typeface.NORMAL), 8, strMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);
TextAppearanceSpan method to customized text with color
/*
*get customized text with color, style
*/
private TextAppearanceSpan getTextAppearanceSpan(int color, int fontStyle) {
ColorStateList blueColor1 = new ColorStateList(new int[][]{new int[]{}}, new int[]{color});
return new TextAppearanceSpan(null, fontStyle, -1, blueColor1, null);
}
If you want use two different fonts in TextView (e.g. toolbar title) you should use Spannable to apply font to each part of text.
The following solution will apply two custom fonts from your resources.
String title = "Nearby- ";
String subtitle = "Friends";
Typeface typefaceBold = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf");
Typeface typefaceNormal = Typeface.createFromAsset(getAssets(), "fonts/Roboto.ttf");
SpannableString spannableTitle = new SpannableString(title + subtitle);
spannableTitle.setSpan (new BetterTypefaceSpan(typefaceBold), 0, title.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
spannableTitle.setSpan (new BetterTypefaceSpan(typefaceNormal), title.length(), spannableTitle.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
toolbar.setText(spannableTitle);
BetterTypefaceSpan.java
// Copy of CalligraphyTypefaceSpan
// https://github.com/chrisjenx/Calligraphy/blob/df1c07f82926831a5c47443bc49f9ff718a4c700/calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyTypefaceSpan.java
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;
public class BetterTypefaceSpan extends MetricAffectingSpan {
private final Typeface typeface;
public BetterTypefaceSpan(final Typeface typeface) {
if (typeface == null) {
throw new IllegalArgumentException("typeface is null");
}
this.typeface = typeface;
}
#Override
public void updateDrawState(final TextPaint drawState) {
apply(drawState);
}
#Override
public void updateMeasureState(final TextPaint paint) {
apply(paint);
}
private void apply(final Paint paint) {
final Typeface oldTypeface = paint.getTypeface();
final int oldStyle = oldTypeface != null ? oldTypeface.getStyle() : 0;
final int fakeStyle = oldStyle & ~typeface.getStyle();
if ((fakeStyle & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}
if ((fakeStyle & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}
paint.setTypeface(typeface);
}
}
Is it possible to change the TextInputLayout error text font for an EditText?
I could only change the color or text size, via app:errorTextAppearance.
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);
}
}
Another method if you like it, you can set Error color or Font both
public static void setErrorTextColor(TextInputLayout textInputLayout, int color, Typeface font) {
try {
Field fErrorView = TextInputLayout.class.getDeclaredField("mErrorView");
fErrorView.setAccessible(true);
TextView mErrorView = (TextView) fErrorView.get(textInputLayout);
Field fCurTextColor = TextView.class.getDeclaredField("mCurTextColor");
fCurTextColor.setAccessible(true);
fCurTextColor.set(mErrorView, color);
mErrorView.setTypeface(font);
} catch (Exception e) {
e.printStackTrace();
}
}
I am trying to change the font of android.support.v7.app.AlertDialogtitle text.
METHOD 1 :
TextView title = (TextView) dialog.findViewById(android.R.id.title); //returns null
METHOD 2 :
final int titleId = context.getResources().getIdentifier("alertTitle", "id", "android");
TextView title = (TextView) dialog.findViewById(titleId); //Also returns null.
Is there any other way to get the title TextView?
Please note I do not want to use a custom layout.
Thanks.
I got it to work using this solution :
final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
Typeface tf = //get the typeface.
CustomTFSpan tfSpan = new CustomTFSpan(tf);
SpannableString spannableString = new SpannableString(title);
spannableString.setSpan(tfSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
alertBuilder.setTitle(spannableString);
AlertDialog dialog = alertBuilder.create();
dialog.show();
CustomTFSpan
public class CustomTFSpan extends TypefaceSpan {
private Typeface typeface;
public CustomTFSpan(Typeface typeface) {
super("");
this.typeface = typeface;
}
#Override
public void updateDrawState(TextPaint ds) {
applyTypeFace(ds, typeface);
}
#Override
public void updateMeasureState(TextPaint paint) {
applyTypeFace(paint, typeface);
}
private static void applyTypeFace(Paint paint, Typeface tf) {
paint.setTypeface(tf);
}
}
Use this one
TextView title = (TextView) dialog.findViewById(R.id.alertTitle);
Without any custom title :)
Your question has already answer here : Change Title Font Of Alert Dialog Box Android
You can simply use a textview and set it as custom title like this : builder.setCustomTitle(tv2);
Create a simple TextView
TextView tv;
And replace
builder.setTitle("My Title");
with
builder.setCustomTitle(tv);
i'm trying to display an arabic text (Right to Left) in my app, but i get words displayed left to right in lines.
I'm using an arabic supporting font and arabic reshaper lib. The text is loaded from strings file.
The app support Android 2.1.
Here a screen shot for the result:
For more details:
public class MainActivity extends Activity {
private TextView tvtest = null;
private static Typeface typeface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvtest = (TextView) findViewById(R.id.tvtest);
tvtest.setText(ArabicUtilities.reshape(getString(R.string.first_part)));
Typeface tf;
tf = GetFont(getApplicationContext());
tvtest.setTypeface(tf);
}
public static final Typeface GetFont(Context context) {
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(),
// "DroidSansFallback.ttf");
"MSHQW.TTF");
}
return typeface;
}
}
Try to set gravity of your TextView.
in code:
`textView.setGravity(...);
or in XML:
android:gravity="..."
Is it possible to use somehow Typeface font definition loaded from assets with EditText in widget ?
The font you want to use needs to reside in the assets/fonts directory, and you access it like so:
Typeface myFont = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
edittext.setTypeface(myFont);
editText.setTypeface(Typeface.createFromAsset(context.getAssets(),"fonts/myfont.ttf"));
Assuming you have this structure of files:
/assets/fonts/myfont.ttf
Please See below code for that, it will solve your problem.
// text view label
TextView mTextView1 = (TextView) findViewById(R.id.TextView1);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), "DroidSansFallback.ttf");
// Applying font
mTextView1.setTypeface(tf);
And see below link for more information.
Android Development – Customize Android Fonts
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Comic.ttf");
youredittext.setTypeface(tf);
I have tried this now. It worked for me. Good luck
Other betther form to implement this and avoid to add the font to all the textviews is extends a TextView (or EditText or ... ) and apply the font on the setTypeface method. With this method you can control bold, italic and other styles.
Here is a code for a class that extends TextView and apply a Roboto font. Moreover it controls some bugs that Android 4.0 has with the html codes when set an Spannable from an HTML
public class TextViewRoboto extends TextView {
public static final String TAG = "TextViewRoboto";
public TextViewRoboto(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TextViewRoboto(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextViewRoboto(Context context) {
super(context);
}
#Override
public void setTypeface(Typeface tf, int style) {
//This is to override eclipse error messages
if (!super.isInEditMode()) {
if (style == Typeface.BOLD)
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Bold.ttf"));
else if (style == Typeface.ITALIC)
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Italic.ttf"));
else
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf"));
}
}
//
// With this code aboid the <b> and <strong> problem on Jelly Bean
//
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}catch (ArrayIndexOutOfBoundsException e){
//Logger.w(TAG, "Problem onMeasure. Set normal text");
setText(getText().toString());
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
#Override
public void setGravity(int gravity){
try{
super.setGravity(gravity);
}catch (ArrayIndexOutOfBoundsException e){
//Logger.w(TAG, "Problem setGravity. Set normal text");
setText(getText().toString());
super.setGravity(gravity);
}
}
#Override
public void setText(CharSequence text, BufferType type) {
try{
super.setText(text, type);
}catch (ArrayIndexOutOfBoundsException e){
//Logger.w(TAG, "Problem on setText. Set normal text");
setText(text.toString());
}
}
public void setHTMLText(CharSequence text, BufferType type) {
String tmpText = text.toString();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
tmpText = tmpText.replace("<strong>", "<b>");
tmpText = tmpText.replace("</strong>", "</b>");
tmpText = tmpText.replace("<em>", "<i>");
tmpText = tmpText.replace("</em>", "</i>");
text = tmpText;
}
try{
super.setText(Html.fromHtml(tmpText), type);
}catch (ArrayIndexOutOfBoundsException e){
//Logger.w(TAG, "Problem on setText. Set normal text");
setText(text.toString());
}
}
}
You can use this
editText.setTypeface(Typeface.SERIF);