Android AlertDialog title font - android

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

Related

How can i make a the text bold which is stored in a string variable?

I want to make the text stored inside a string variable to bold.
String buttonText = t.getText().toString();
String val = map.get(buttonText);
new MaterialDialog.Builder(LearningMode.this)
.iconRes(BalloonColor.get(2))
.limitIconToDefaultSize()
.title("Meaning")
.content(buttonText+"\n"+val)
.positiveText("Continue")
.cancelable(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
mover.resume();
}
})
.show();
at .content(buttonText+"\n"+val)
i want the string stored inside this to become bold.
i have tried html.fromhtml it is not working
like this Html.fromHtml(" < b > "+buttonText+" < / b >")
added space in the above as it is converting to bold
and other methods like declaring in strings.xml with < b > wont work here as i'm dealing it programmatically here!
ultimately when the string button text is displayed in the output sholud be bold.
i have already referred this Set TextView text from html-formatted string resource in XML
Update:
There is no textview used.
Someone please help!
The MaterialDialog.Builder class's content(CharSequence) method should work just fine for making text bold, as long as you pass in some CharSequence that supports bold text. I know you said Html.fromHtml() isn't working, but in my tests it works perfectly. Here's a really simple activity that's a proof of concept:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
String myString = "test";
new MaterialDialog.Builder(this)
.title("Hello world")
.content(Html.fromHtml("this is a <b>" + myString + "</b>"))
.positiveText("OK")
.show();
}
}
try this:
buttonText.setTypeface(null, Typeface.BOLD);
You may use SpannableString for it. say you ave a TextView called txt then the code is:
SpannableStringBuilder sb = new SpannableStringBuilder("HELLOO");
StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);
sb.setSpan(bss, 0, sb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
txt.setText(sb);
Updated
As I seen in material dialog library it has bug for that so try below code
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new MaterialDialog.Builder(getActivity())
.title(R.string.about)
.positiveText(R.string.dismiss)
.content(fromHtml(getString(R.string.about_body)))
.contentLineSpacing(1.6f)
.build();
}
#SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(html);
}
return result;
}
}
for more https://github.com/afollestad/material-dialogs/issues/1290

How to customise toolbar title font, I need to give two different fonts to Toolbar title. [duplicate]

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

Change TextInputLayout error font?

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

change the colour and font of text of title in dialog box

I want to change the font and colour of the title in dialog box, I want change font, size, and colour, what should I do?
here is my code,
ivworknggroup.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(Ourwork.this);
dialog.setContentView(R.layout.nggroup);
dialog.setTitle("N.G.GROUP");
TextView tvnggroup1 = (TextView) dialog.findViewById(R.id.tvnggroup1);
TextView tvnggroup2 =(TextView)dialog.findViewById(R.id.tvnggroup2);
Typeface typeFace1 = Typeface.createFromAsset(getAssets(),"fonts/antennalight.ttf");
tvnggroup1.setTypeface(typeFace1);
Typeface typeFace = Typeface.createFromAsset(getAssets(),"fonts/antennabold.ttf");
tvnggroup2.setTypeface(typeFace);
tvnggroup2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.nggroupindia.com/"));
startActivity(browserIntent);
}
});
dialog.show();
}
});
can any one help me?
thank u.
Well i had a similar situation once, but this is what got it solved for me.
Dialog sortDialog = new Dialog(getApplicationContext());
sortDialog.setContentView(R.layout.adtype_alertdialog);
sortDialog.setTitle("N.G.GROUP");
int dividerId = sortDialog
.getContext()
.getResources()
.getIdentifier("android:id/titleDivider", null,
null);
if (dividerId != 0) {
View divider = sortDialog.findViewById(dividerId);
divider.setBackgroundColor(getResources().getColor(
R.color.yellow));
}
TextView tv = (TextView) sortDialog
.findViewById(android.R.id.title);
if (tv != null) {
tv.setTextColor(getResources().getColor(R.color.yellow));
}
sortDialog.show();
android:id/titleDivider & android.R.id.title in an identifier found in the alert_dialog.xml in your SDK folder
you should use custom view for title of your dialog maybe this link help you
how to include custom title view with in AlertDialog in android?
try this way
private String HALLOWEEN_ORANGE = "#FF7F27";
AlertDialog dialog = new AlertDialog.Builder(this).setMessage("Message").show();
setTitle("Title").
setTitleColor(HALLOWEEN_ORANGE).
setDividerColor(HALLOWEEN_ORANGE).
TextView textView = (TextView) dialog.findViewById(android.R.id.message);
textView.setTextSize(10);//to change font size
textView.setTextColor(Color.RED); // to change color
//to change font family
Typeface face = Typeface.createFromAsset(getAssets(),"font/fontFileName.ttf");
textView.setTypeface(face);

clickable word inside TextView in android

I have TextView with text that changed dynamically. This text contain strings like <a href='myWord'>myWord</a>. I want that after click to this "link" myWord appear in the EditText in the same activity.
This is my code:
txt.setText(Html.fromHtml("...<a href='link'>link</a>..."));
txt.setMovementMethod(LinkMovementMethod.getInstance());
It's work well for URLs inside href attribute, but there is an error for another format.
I found a lot of similar questions on the StackOverflow but all of them were about url links. In my app I want create "link" inside activity.
In general, I can change tag to some another if it's depend...
Please help me!
Thank you!
-----SOLVED-----
Thank you Jacob Phillips for idea!
May it will be interesting someone in future.
This is a code:
//This is my string;
String str = "<b>Text</b> which contains one <a href='#'>link</a> and another <a href='#'>link</a>";
//TextView;
TextView txt = new TextView(this);
//Split string to parts:
String[] devFull = data[v.getId()][1].split("<a href='#'>");
//Adding first part:
txt.append(Html.fromHtml(devFull[0]));
//Creating array for parts with links (they amount always will devFull.length-1):
SpannableString[] link = new SpannableString[devFull.length-1];
//local vars:
ClickableSpan[] cs = new ClickableSpan[devFull.length-1];
String linkWord;
String[] devDevFull = new String[2];
for(int i=1; i<devFull.length; i++){
//obtaining 'clear' link
devDevFull = devFull[i].split("</a>");
link[i-1] = new SpannableString(devDevFull[0]);
linkWord = devDevFull[0];
cs[i-1] = new ClickableSpan(){
private String w = linkWord;
#Override
public void onClick(View widget) {
// here you can use w (linkWord)
}
};
link[i-1].setSpan(cs[i-1], 0, linkWord.length(), 0);
txt.append(link[i-1]);
try{
txt.append(Html.fromHtml(devDevFull[1]));
}
catch(Exception e){}
}
This should do the trick. Just change your edittext's text in the OnClickListener. It may be able to be reduced but this should work.
private void foo() {
SpannableString link = makeLinkSpan("click here", new View.OnClickListener() {
#Override
public void onClick(View v) {
// respond to click
}
});
// We need a TextView instance.
TextView tv = new TextView(context);
// Set the TextView's text
tv.setText("To perform action, ");
// Append the link we created above using a function defined below.
tv.append(link);
// Append a period (this will not be a link).
tv.append(".");
// This line makes the link clickable!
makeLinksFocusable(tv);
}
/*
* Methods used above.
*/
private SpannableString makeLinkSpan(CharSequence text, View.OnClickListener listener) {
SpannableString link = new SpannableString(text);
link.setSpan(new ClickableString(listener), 0, text.length(),
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
return link;
}
private void makeLinksFocusable(TextView tv) {
MovementMethod m = tv.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (tv.getLinksClickable()) {
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
/*
* ClickableString class
*/
private static class ClickableString extends ClickableSpan {
private View.OnClickListener mListener;
public ClickableString(View.OnClickListener listener) {
mListener = listener;
}
#Override
public void onClick(View v) {
mListener.onClick(v);
}
}
Better approach is
SpannableString ss = new SpannableString("Android is a Software stack");
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
startActivity(new Intent(MyActivity.this, NextActivity.class));
}
};
ss.setSpan(clickableSpan, 22, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//where 22 and 27 are the starting and ending index of the String. Now word stack is clickable
// onClicking stack it will open NextActiivty
TextView textView = (TextView) findViewById(R.id.hello);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
You can use below code;
SpannableString myString = new SpannableString(Html.fromHtml("Please "+"<font color=\"#F15d36\"><u>"+"login"+"</u></font>" +" or "+ "<font color=\"#F15d36\"><u>"+"sign up"+ "</u></font>"+" to begin your YupIT experience"));
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
Toast.makeText(getContext(),"dfsgvdfs",Toast.LENGTH_SHORT).show();
}
};
ClickableSpan clickableSpan1 = new ClickableSpan() {
#Override
public void onClick(View textView) {
Toast.makeText(getContext(),"dfsgvdfs",Toast.LENGTH_SHORT).show();
}
};
myString.setSpan(clickableSpan,6,12,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
myString.setSpan(clickableSpan1,15,23,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
myString.setSpan(new ForegroundColorSpan(Color.parseColor("#F15d36")),6, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myString.setSpan(new ForegroundColorSpan(Color.parseColor("#F15d36")),15,23, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tvFound.setMovementMethod(LinkMovementMethod.getInstance());
tvFound.setText(myString);
The best workaround I know is to create your own Button class. You could make the Button have a transparent background so that only the text is seen by the user. Then when the Button is pressed down change the TextColor and TextStyle of the button to be a darker color and underlined. This will work exactly as a link does. You can then use startActivity to go to the appropriated activity. You should not use hyperlinks to connect to other activities within your application.
My personal opinion would be to make a second textview containing the text that you want to be your link. Then you could do your action in the onClick of this second textView . Also as zzzzzzzzzzz stated above, you could choose to change the font properties of that text to whatever you want once it has been clicked.
To make it full answer with mixing answers;
private void textAreaInit()
{
String str = "<a href='#'>Link 1</a> and <a href='#'>Link2</a> is here.";
TextView tv = mConfirmText;
String[] devFull = str.split("<a href='#'>");
tv.append(Html.fromHtml(devFull[0]));
SpannableString[] link = new SpannableString[devFull.length-1];
ClickableSpan[] cs = new ClickableSpan[devFull.length-1];
String linkWord;
String[] devDevFull = new String[2];
for(int i=1; i<devFull.length; i++)
{
//obtaining 'clear' link
devDevFull = devFull[i].split("</a>");
link[i-1] = new SpannableString(devDevFull[0]);
linkWord = devDevFull[0];
final String a = linkWord;
cs[i-1] = new ClickableSpan()
{
private String w = a;
#Override
public void onClick(View widget) {
if(w.equals("Link 1"))
{
Intent intent = new Intent(PrintPropertiesActivity.this, ViewerAcivity.class);
intent.putExtra("title", "Link1");
intent.putExtra("uri", "link1");
intent.putExtra("type", "1");
startActivity(intent);
}
else
{
Intent intent = new Intent(PrintPropertiesActivity.this, ViewerAcivity.class);
intent.putExtra("title", "Link2");
intent.putExtra("uri", "link2");
intent.putExtra("type", "2");
startActivity(intent);
}
}
};
link[i-1].setSpan(cs[i-1], 0, linkWord.length(), 0);
tv.append(link[i-1]);
try{
tv.append(Html.fromHtml(devDevFull[1]));
}
catch(Exception e){}
}
makeLinksFocusable(tv);
}
private void makeLinksFocusable(TextView tv) {
MovementMethod m = tv.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (tv.getLinksClickable()) {
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}

Categories

Resources