Change TextInputLayout error font? - android

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

Related

Android AlertDialog title font

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

Custom Typeface Span not working

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

Android: Change the background color of a ClickableSpan when clicked

I have a SpannableString with a ClickableSpan as follows
for (int i = 0; i < items.size(); i++) {
final SpannableString span = new SpannableString(items.get(i));
final int index=i;
span.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
}
#Override
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.LTGRAY);
ds.setUnderlineText(false);
}
}, 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(span);
}
//my text view
txt.setText(builder);
txt.setMovementMethod(LinkMovementMethod.getInstance());
what I want to do is to change the foreground color of the span when clicked.
how can I do this ?
If you're looking to get rid of the green highlight on selection, this is what you want to know:
Apparently, overriding public void updateDrawState(TextPaint ds) in your custom class would not affect the highlight color. It is only used for setting the underline color (or hiding/showing it).
All you need to do is:
textView.setHighlightColor(Color.TRANSPARENT);
where textView is what contains the ClickableSpan.
Hope it works for all of you.
Feel free to ask any related question.
I extended the clickableSpan class and passed it a flag that lets me know that I should highlight it.
SpannableStringBuilder tag;
.... tag.setSpan(new WordSpan(i, tokens[i], wordtohighlitedID) {
.....
import android.graphics.Color;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;
public class WordSpan extends ClickableSpan
{
private int id;
private TextPaint textpaint;
public boolean shouldHilightWord = false;
public WordSpan(int anID, String txt, int selected) {
id =anID;
// if the word selected is the same as the ID set the highlight flag
if(selected == id) {
shouldHilightWord = true;
}
}
#Override
public void updateDrawState(TextPaint ds) {
textpaint = ds;
ds.setColor(ds.linkColor);
if(shouldHilightWord){
textpaint.bgColor = Color.GRAY;
textpaint.setARGB(255, 255, 255, 255);
}
//Remove default underline associated with spans
ds.setUnderlineText(false);
}
public void changeSpanBgColor(View widget){
shouldHilightWord = true;
updateDrawState(textpaint);
widget.invalidate();
}
#Override
public void onClick(View widget) {
// TODO Auto-generated method stub
}
/**
* This function sets the span to record the word number, as the span ID
* #param spanID
*/
public void setSpanTextID(int spanID){
id = spanID;
}
/**
* Return the wordId of this span
* #return id
*/
public int getSpanTextID(){
return id;
}
}
Use this:
view.setSelector(new ColorDrawable(Color.BLUE));

How to get rid of the underline in a Spannable String with a Clickable Object?

I have a Spannable Object with a Clickable Object set to it. When the Spannable String is displayed in the TextView it has blue text and a blue underline (indicating to the user that this Text is Clickable). My problem is how can I prevent appearing the blue underline in TextView?
Use the below code and try
String mystring =" Hello";
SpannableString ss= new SpannableString(mystring);
ss.setSpan(new MyClickableSpan(mystring), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
class MyClickableSpan extends ClickableSpan{// extend ClickableSpan
String clicked;
public MyClickableSpan(String string) {
super();
clicked = string;
}
#Override
public void onClick(View tv) {
Toast.makeText(MainActivity.this,clicked , Toast.LENGTH_SHORT).show();
}
#Override
public void updateDrawState(TextPaint ds) {// override updateDrawState
ds.setUnderlineText(false); // set to false to remove underline
}
}
This works for me. No need to create custom ClickableSpan class. Just override updateDrawState(TextPaint ds).
SpannableString span = new SpannableString("Some text");
ClickableSpan clickSpan = new ClickableSpan() {
#Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ds.linkColor); // you can use custom color
ds.setUnderlineText(false); // this remove the underline
}
#Override
public void onClick(View textView) {
// handle click event
}
};
span.setSpan(clickSpan, 5, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTextView.setText(span);
Raghunandan's answer works perfectly for me. Here is a pared-down version of it:
public abstract class NoUnderlineClickableSpan extends ClickableSpan {
public void updateDrawState(TextPaint ds) {
ds.setUnderlineText(false);
}
}
Override updateDrawState method of ClickableSpan class
String mystring =" Hello";
SpannableString ss= new SpannableString(mystring);
ss.setSpan(new MyClickableSpan(mystring), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
class MyClickableSpan extends ClickableSpan{// extend ClickableSpan
String clicked;
public MyClickableSpan(String string) {
// TODO Auto-generated constructor stub
super();
clicked =string;
}
public void onClick(View tv) {
Toast.makeText(MainActivity.this,clicked ,
Toast.LENGTH_SHORT).show();
}
public void updateDrawState(TextPaint ds) {// override updateDrawState
ds.setUnderlineText(false); // set to false to remove underline
}
For changing color of spannable String
SpannableString ss = new SpannableString("android Stack Overflow");
ForegroundColorSpan fcs=newForegroundColorSpan(Color.parseColor("#01579B"));
ss.setSpan(fcs, 8,13, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
spannableStringObject.toString();
Edit
SpannableString ss = getYourSpannableString();
UnderlineSpan[] uspans = ss.getSpans(0, ss.length(), UnderlineSpan.class);
for (UnderlineSpan us : uspans) {
ss.removeSpan(us);
}
Will remove all the UnderlineSpans from the Spannable.
simplest way is
string1 = new SpannableString("By Tapping Register You Agree To The \nTerms And Conditions");
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(getApplicationContext(),"clicked",Toast.LENGTH_SHORT).show();
}
#Override
public void updateDrawState(TextPaint ds) {
ds.setUnderlineText(false); // this line removes underline
}
};
text_terms.setMovementMethod(LinkMovementMethod.getInstance());
string1.setSpan(clickableSpan,37,string1.length(),0);
text_terms.setText(string1);
Based on the answer of #Sai Gopi Me
in Kotlin:
val clickableSpan: ClickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
// some action here
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = false
}
}
}
Try the below code to remove underlined and clicked event on multiple words in textview :
String str="Angelina Clapped For Lester Kang";
Spannable span = Spannable.Factory.getInstance().newSpannable(str);
// 0 to 8 start and index of Angelina
span.setSpan(new ClickableSpan(str), 0, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// 21 to 32 start and index of Lester Kang
span.setSpan(new ClickableSpan(str), 21, 32, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(span);
class ClickableSpan extends ClickableSpan{
String clicked;
public ClickableSpan (String string) {
super();
}
public void onClick(View v) {
Toast.makeText(MyActivity.this,""+((TextView)v).getText().toString(),Toast.LENGTH_SHORT).show();
}
public void updateDrawState(TextPaint ds) {
// override updateDrawState
ds.setUnderlineText(false); // set to false to remove underline
}
}
ANURAG RASTOGI's answer saved the day for me! I already have a formatted SpannableString on which I wanted to apply a ClickableSpan:
spannableString.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
// Do something...
}
// Prevent
// ds.setColor(ds.linkColor);
// ds.setUnderlineText(true);
// in: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/text/style/ClickableSpan.java
// from executing.
#Override
public void updateDrawState(#NonNull TextPaint ds) {
// super.updateDrawState(ds);
}
},0, spannableString.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
The updateDrawState overrides the updateDrawState in the ClickableSpan class in Android, and by not calling super.updateDrawState it will not get executed.
All text formatting already present in spannableString will be preserved.
If you do not want any pre-applied attributes do not call super.updateDrawState(). On overriding updateDrawState(object:Textpaint) with help of object you can apply or call different functions present in Text Paint.

Use Typeface with EditText in widget

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

Categories

Resources