Can I underline text in an Android layout? - android

How can I define underlined text in an Android layout xml file?

It can be achieved if you are using a string resource xml file, which supports HTML tags like <b></b>, <i></i> and <u></u>.
<resources>
<string name="your_string_here"><![CDATA[This is an <u>underline</u>.]]></string>
</resources>
If you want to underline something from code use:
TextView textView = (TextView) view.findViewById(R.id.textview);
SpannableString content = new SpannableString("Content");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
textView.setText(content);

You can try with
textview.setPaintFlags(textview.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

Strings.xml file content:
<resource>
<string name="my_text">This is an <u>underline</u>.</string>
</resources>
Layout xml file shold use the above string resource with below properties of textview, as shown below:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/my_text"
android:selectAllOnFocus="false"
android:linksClickable="false"
android:autoLink="all"
/>

The "accepted" answer above does NOT work (when you try to use the string like textView.setText(Html.fromHtml(String.format(getString(...), ...))).
As stated in the documentations you must escape (html entity encoded) opening bracket of the inner tags with <, e.g. result should look like:
<resource>
<string name="your_string_here">This is an <u>underline</u>.</string>
</resources>
Then in your code you can set the text with:
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(String.format(getString(R.string.my_string), ...)));

For Button and TextView this is the easiest way:
Button:
Button button = (Button) findViewById(R.id.btton1);
button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Textview:
TextView textView = (TextView) findViewById(R.id.textview1);
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

In Kotlin extension function can be used. This can only be used from code, not xml.
fun TextView.underline() {
paintFlags = paintFlags or Paint.UNDERLINE_TEXT_FLAG
}
Usage:
tv_change_number.underline()
tv_resend_otp.underline()

To do that in Kotlin:
yourTextView.paint?.isUnderlineText = true

One line solution
myTextView.setText(Html.fromHtml("<p><u>I am Underlined text</u></p>"));
It is bit late but could be useful for someone.

check out the underscored clickable button style:
<TextView
android:id="#+id/btn_some_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn_add_contact"
android:textAllCaps="false"
android:textColor="#57a0d4"
style="#style/Widget.AppCompat.Button.Borderless.Colored" />
strings.xml:
<string name="btn_add_contact"><u>Add new contact</u></string>
Result:

A cleaner way instead of the
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
method is to use
textView.getPaint().setUnderlineText(true);
And if you need to later turn off underlining for that view, such as in a reused view in a RecyclerView, textView.getPaint().setUnderlineText(false);

If you want to achieve this in XML, declare your string in resource and put that resource value into underline tag (<u></u>) of HTML.
in TextView, add
android:text="#string/your_text_reference"
And in string resource value,
<string name="your_text_reference"><u>Underline me</u></string>
If you want to achieve this programmatically, for Kotlin use
textView.paintFlags = textView.paintFlags or Paint.UNDERLINE_TEXT_FLAG
or,
textView.text = Html.fromHtml("<p><u>Underline me</u></p>")

I know this is a late answer, but I came up with a solution that works pretty well... I took the answer from Anthony Forloney for underlining text in code and created a subclass of TextView that handles that for you. Then you can just use the subclass in XML whenever you want to have an underlined TextView.
Here is the class I created:
import android.content.Context;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created with IntelliJ IDEA.
* User: Justin
* Date: 9/11/13
* Time: 1:10 AM
*/
public class UnderlineTextView extends TextView
{
private boolean m_modifyingText = false;
public UnderlineTextView(Context context)
{
super(context);
init();
}
public UnderlineTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
public UnderlineTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init();
}
private void init()
{
addTextChangedListener(new TextWatcher()
{
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
//Do nothing here... we don't care
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
//Do nothing here... we don't care
}
#Override
public void afterTextChanged(Editable s)
{
if (m_modifyingText)
return;
underlineText();
}
});
underlineText();
}
private void underlineText()
{
if (m_modifyingText)
return;
m_modifyingText = true;
SpannableString content = new SpannableString(getText());
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
setText(content);
m_modifyingText = false;
}
}
Now... whenever you want to create an underlined textview in XML, you just do the following:
<com.your.package.name.UnderlineTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="This text is underlined"
android:textColor="#color/blue_light"
android:textSize="12sp"
android:textStyle="italic"/>
I have added additional options in this XML snippet to show that my example works with changing the text color, size, and style...
Hope this helps!

The most recent approach of drawing underlined text is described by Romain Guy on medium with available source code on GitHub.
This sample application exposes two possible implementations:
A Path-based implementation that requires API level 19
A Region-based implementation that requires API level 1

Just use the attribute in string resource file e.g.
<string name="example"><u>Example</u></string>

I used this xml drawable to create a bottom-border and applied the drawable as the background to my textview
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle" >
<solid android:color="#android:color/transparent" />
</shape>
</item>
<item android:top="-5dp" android:right="-5dp" android:left="-5dp">
<shape>
<solid android:color="#android:color/transparent" />
<stroke
android:width="1.5dp"
android:color="#color/pure_white" />
</shape>
</item>
</layer-list>

Most Easy Way
TextView tv = findViewById(R.id.tv);
tv.setText("some text");
setUnderLineText(tv, "some");
Also support TextView childs like EditText, Button, Checkbox
public void setUnderLineText(TextView tv, String textToUnderLine) {
String tvt = tv.getText().toString();
int ofe = tvt.indexOf(textToUnderLine, 0);
UnderlineSpan underlineSpan = new UnderlineSpan();
SpannableString wordToSpan = new SpannableString(tv.getText());
for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
ofe = tvt.indexOf(textToUnderLine, ofs);
if (ofe == -1)
break;
else {
wordToSpan.setSpan(underlineSpan, ofe, ofe + textToUnderLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
}
}
}
If you want
- Clickable underline text?
- Underline multiple parts of TextView?
Then Check This Answer

A simple and flexible solution in xml:
<View
android:layout_width="match_parent"
android:layout_height="3sp"
android:layout_alignLeft="#+id/your_text_view_need_underline"
android:layout_alignRight="#+id/your_text_view_need_underline"
android:layout_below="#+id/your_text_view_need_underline"
android:background="#color/your_color" />

another solution is to a create a custom view that extend TextView as shown below
public class UnderLineTextView extends TextView {
public UnderLineTextView(Context context) {
super(context);
this.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
}
public UnderLineTextView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
this.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
}
}
and just add to xml as shown below
<yourpackage.UnderLineTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="underline text"
/>

try with Class
for java
textview.setPaintFlags(textview.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
for Kotlin
textview.setPaintFlags(textview.getPaintFlags() or Paint.UNDERLINE_TEXT_FLAG)

try this code
in XML
<resource>
<string name="my_text"><![CDATA[This is an <u>underline</u>]]></string>
</resources>
in Code
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(getString(R.string.my_text)));
Good Luck!

I simplified Samuel's answer:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!--https://stackoverflow.com/a/40706098/4726718-->
<item
android:left="-5dp"
android:right="-5dp"
android:top="-5dp">
<shape>
<stroke
android:width="1.5dp"
android:color="#color/colorAccent" />
</shape>
</item>
</layer-list>

Very compact, kotlin version:
tvTitle.apply {
text = "foobar"
paint?.isUnderlineText = true
}

Go to strings.xml resource file
Add a string in the resource file with an HTML underline tag where necessary.
strings.xml HTML underline sample
Call the string resource ID in your Java code as following:
sampleTextView.setText(R.string.sample_string);
The output should have the word "Stackoverflow" underlined.
Furthermore, the following code will not print the underline:
String sampleString = getString(R.string.sample_string);
sampleTextView.setText(sampleString);
Instead, use the following code to retain rich text format:
CharSequence sampleString = getText(R.string.sample_string);
sampleTextView.setText(sampleString);
"You can use either getString(int) or getText(int) to retrieve a string. getText(int) retains any rich text styling applied to the string." Android documentation.
Refer to the documentation: https://developer.android.com/guide/topics/resources/string-resource.html
I hope this helps.

The top voted answer is right and simplest. However, sometimes you may find that not working for some font, but working for others.(Which problem I just came across when dealing with Chinese.)
Solution is do not use "WRAP_CONTENT" only for your TextView, cause there is no extra space for drawing the line. You may set fixed height to your TextView, or use android:paddingVertical with WRAP_CONTENT.

HtmlCompat.fromHtml(
String.format(context.getString(R.string.set_target_with_underline)),
HtmlCompat.FROM_HTML_MODE_LEGACY)
<string name="set_target_with_underline"><u>Set Target<u> </string>
Note the Escape symbol in xml file

Its quite late to answer this but suppose if anyone wants to get the text dynamically then they can use this simple one line in their java code which works:
textView.setText(Html.fromHtml("<p><u>" + get_name + "</u></p>"));

<com.google.android.material.textfield.TextInputEditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:backgroundTint="#android:color/transparent"
android:hint="#string/search_url"
android:textColor="#color/coffee_color"
android:textColorHint="#color/coffee_color"
/>

I had a problem where I'm using a custom font and the underline created with the resource file trick (<u>Underlined text</u>) did work but Android managed to transform the underline to a sort of strike trough.
I used this answer to draw a border below the textview myself: https://stackoverflow.com/a/10732993/664449. Obviously this doesn't work for partial underlined text or multilined text.

Related

I need help in the custom Font and TextView

I'm new in android working on an app that gives the user info about all font's of Google.
For that, I need to make an app with a TextView Something like this
On click of the TextView, the font will change With text.
I'm thinking about using onclicklistener
you can put "your_font.ttf" file in asset folder then import it with
Typeface custom_font_1 = Typeface.createFromAsset(getAssets(), "your_font.ttf");
then assign it to your showCaseTextView with this
showCaseTextView.setTypeFace(custom_font_1);
then in your onClickListener of showCaseTextView to change your specifiedTextView font do like this
specifiedTextView.setTypeFace(custom_font_1);
and repeat it for other fonts.
You can implement your own custom font with TextView, EditText, Button etc.. by using android attributes.
How to
-Here are some steps to use:
1.Create attribute file (res->values->attrs.xml)
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<declare-styleable name="TextElement">
<attr name="font" format="string"/>
<attr name="underline" format="boolean"/>
</declare-styleable>
</resources>
2.Create Custom TextView class (anywhere in java folder)
3. Use attributes inside your layout file
4. and just run your code.
Here is the full example of your question, you can go through this exmaple:
Full Demonstration
Have 2 way to archive this
1st way
public class FontCache {
private static HashMap<String, Typeface> fontCache = new HashMap<>();
public static Typeface getTypeface(String fontname, Context context) {
Typeface typeface = fontCache.get(fontname);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(context.getAssets(), fontname);
} catch (Exception e) {
return null;
}
fontCache.put(fontname, typeface);
}
return typeface;
}
}
This caches the fonts while minimizing the number of accesses to the assets. Now, since we've a method to access our custom font, let's implement a class, which extends TextView.
Extending TextView
Next, we'll create a new Java class, which extends TextView. This allows us to use that class in all XML views. It inherits all functionality and properties of a regular TextView; but adds our custom font.
Once again, we're taking a peek at the source code of our eat foody project. The code might look complex for a second, but is straight-forward:
public class EatFoodyTextView extends TextView {
public EatFoodyTextView(Context context) {
super(context);
applyCustomFont(context);
}
public EatFoodyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context);
}
public EatFoodyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context);
}
private void applyCustomFont(Context context) {
Typeface customFont = FontCache.getTypeface("SourceSansPro-Regular.ttf", context);
setTypeface(customFont);
}
}
The first three methods are just constructors, which we override to call a single method applyCustomFont(). That method is the important piece of the puzzle. It simply gets the (hopefully cached) font from our FontCache class. Lastly, we've to call setTypeface() with the font and we're almost done. In case you're wondering, we can call the setTypeface() directly (and not on a TextView object), since we're extending the TextView class.
Using the Class
You might wonder, if so much preparation is worth the effort. In this section you'll see that it is indeed. Because all you've left to do is use the class in an XML view and it automatically has your custom font. There is no Java code necessary!
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.futurestudio.foody.views.EatFoodyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:layout_marginBottom="24dp"/>
</RelativeLayout>
As you can see, you can continue to use all niceties (e.g. textSize, textColor) of TextView. Now, just replace all elements with the class we just created, for example and you applied your custom font everywhere!
(Ref: https://futurestud.io/tutorials/custom-fonts-on-android-extending-textview)
2nd way
Follow Google guide support from API 26 (Android 8) https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml
Make change between textview to change font
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textview_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:layout_marginBottom="24dp"/>
<com.futurestudio.foody.views.EatFoodyTextView
android:id="#+id/textview_custom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:visibility="gone"
android:layout_marginBottom="24dp"/>
</RelativeLayout>
attention at android:visibility="gone"
in Activity you use this code to toggle between 2 TextViews
final TextView normalTextView = findViewById(R.id.textview_normal);
final TextView customTextView = findViewById(R.id.textview_custom);
normalTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
normalTextView.setVisibility(View.GONE);
customTextView.setVisibility(View.VISIBLE);
}
});
customTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
normalTextView.setVisibility(View.VISIBLE);
customTextView.setVisibility(View.GONE);
}
});

Add static text before or after a TextView

I'm new to Android Dev and I try to figure a gently way to add static text before and after a dynamic part in a TextView, without having to add 2 other TextView or add these content each time I update the dynamic part of my TextView.
Something just like ::after or ::before with content propertie in CSS.
Something which could look like this :
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10"
android:textAfter=" km/h" />
I digged Google up and down (went to 3rd page sometimes) but I couldn't find any way to do this trick which appear pretty basic to me.
In my opinion, you just need a custom TextView. Then you can make one.
First, declare custom attributes for your CustomTextView. Create a new file named attrs.xml in /res/values. fill it with code below.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTextView">
<attr name="textAfter" format="string"/>
</declare-styleable>
</resources>
Second, Create Your CustomTextView as a java file. That's simple. You just need get the value of attribute of textAfter and set it to the tail of the text when setText is invoked.
public class CustomTextView extends TextView {
private String mTextAfter;
public CustomTextView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
mTextAfter = array.getString(R.styleable.CustomTextView_textAfter);
array.recycle();
}
#SuppressLint("SetTextI18n")
#Override
public void setText(CharSequence text, BufferType type) {
super.setText(text + (TextUtils.isEmpty(mTextAfter) ? "" : mTextAfter), type);
}
}
Thrid, use the CustomTextView in layout.(Do NOT forget to add xmlns:app="http://schemas.android.com/apk/res-auto" in the root view of your layout)
<!-- your package name -->
<com.xxx.xxx.CustomTextView
android:id="#+id/mtv"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:textAfter=" km/h" />
Fourth, use it in XXXActivity.java.
//TextView mtv = (TextView) findViewById(R.id.mtv));// this is worked too
CustomTextView mtv = ((CustomTextView) findViewById(R.id.mtv));
mtv.setText("18");//do NOT put int value of 18 in it, or it will be treated as a resource id
Then you will see, the km/h is added after 18.
You can use string resource for dynamic text with a predefined format using %d or %1$d.
For example, if you want to show something like 10 km/h, you can use string resource like this:
<string name="range_in_kilometer_per_hour">%d km/h</string>
Then you can set it via code with:
TextView tvKm;
...
int currentKm = 10;
String kmValue = getString(R.string.range_in_kilometer_per_hour, currentKm);
tvKm.setText(kmValue);
Or if you want to show something like 10 km each 1 hour, you can use something like:
<string name="range_in_kilometer_per_hour">%1$d km each %2$d hour</string>
Then set it to your TextView with:
int currentKm = 10;
int hour = 1;
String kmValue = getString(R.string.range_in_kilometer_per_hour, currentKm, hour);
tvKm.setText(kmValue);
If you want to use string instead of an integer, you can use %s for single text replacement, or %1$s for multiple text replacement.
You need to remember that the means of 1 in %1$s is the position of the text replacement.
Read more at:
String Resources
getString
I think you should do something like this
remove text in xml i.e. km/hr
go to your activity java file let it be activity_main.java
Dynamically get the value of speed
say for
int speed;
then in textview(xml)
assign any id android:id="#+id/speedTextView"
in java
assign speed value
TextView speedWithUnit = (TextView) findViewById(R.id.speedTextView);
and
speedWithUnit.setText(speed+"km/hr");
Hope this help

How do you create an XML-friendly control based on a layout?

I've created a custom control which is a subclass of LinearLayout. I have also created a layout file on which this control is based. Finally I have defined attributes which I parse in the constructor to set my custom properties on. As an example, one of those properties is called 'text'.
Here's a simplified version of my code (I've stripped out a lot of the other properties and such so we can just focus on the one property 'text'):
First, the class (our custom version of a RadioButton)...
public class RadioButton extends LinearLayout
{
private TextView textView;
public RadioButton(Context context, AttributeSet attrs)
{
super(context, attrs);
initAttributes(attrs, 0);
}
private void initAttributes(AttributeSet attrs, int defStyle)
{
final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CheckBoxView, defStyle, 0);
text = a.getString(R.styleable.RadioButton_text);
if(text == null)
text = "Not set";
a.recycle();
}
#Override
protected void onFinishInflate()
{
super.onFinishInflate();
textView = (TextView)findViewById(R.id.textView);
textView.setText(text);
}
private String text;
public String getText() { return text; }
public void setText(String newValue)
{
text = newValue;
if(textView != null)
textView.setText(text);
}
}
Here's the attrs.xml file...
<resources>
<attr name="text" format="string" />
<declare-styleable name="RadioButton">
<attr name="text" />
</declare-styleable>
</resources>
And here's the 'reusable_radiobutton.xml' layout file (Note: the internal RadioButtonView is a custom-rendered View and works fine):
<?xml version="1.0" encoding="utf-8"?>
<com.somedomain.reusable.ui.RadioButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<com.somedomain.reusable.ui.RadioButtonView
android:id="#+id/radioButtonView"
style="#style/DefaultRadioButtonView" />
<TextView
android:id="#+id/textView"
style="#style/DefaultRadioButtonText" />
</com.somedomain.reusable.ui.RadioButton>
With the above, users of my control can simply include it in their own layout files, like so...
<include android:id="#+id/someRadioButton"
layout="#layout/reusable_radiobutton" />
The in their code, using the following, they can get that instance and do with it what they wish, like so...
RadioButton someRadioButton = (RadioButton)findViewById(R.id.someRadioButton);
someRadioButton.text = "Woot!";
This works as expected.
However, this doesn't...
<include android:id="#+id/someRadioButton"
layout="#layout/reusable_radiobutton"
app:text="Hello World!" />
It gives me a warning, but otherwise ignores it.
I then tried this...
<com.somedomain.reusable.ui.RadioButton
app:text="Hello World!" />
While this does instantiate my control and does pass 'Hello World!' to my property via the attributes, nothing actually loads or even associates the layout file to my class so nothing appears on the screen!
So how can I create a custom view, based on a layout, which other developers can simply reference in their own layout files while also allowing them to set custom attributes?
Hope that all made sense! :)
Note: The Android documentation talks about exactly what I'm after, 'Compound Controls' as referenced here, but they don't give an example of using a layout to define the compounded control. However, I feel that was pretty close.
Found it here on SO. I didn't realize you could inflate something into yourself. That and using the Merge tag took care of it for me.

Make text bold, italic or underline while writing in edittext

I want my editText to able to write text in bold, italic and underline along with normal text.
Eg:
The weather is nice today.
I know I can use html tags but I want to perform these operations while writing in the edittext.
What I have tried:
//here textEdits is my model to store the string. As I have multiple editTexts in the activity.
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if(isBold){
String textsequence = textEdits.get(position).getTextString();
if(i > 0){
String sequence = charSequence.subSequence(0, i).toString() +"<b>"+ charSequence.subSequence(i,i+i3).toString() + "</b>";
textEdits.get(position).setTextString(sequence.toString());
editTextcurrrent.setText(Html.fromHtml(sequence.toString()));
editTextcurrrent.setSelection(i+i3);
}
}
}
else {
textEdits.get(position).setTextString(charSequence.toString());
}
}
}
The problem:
The charSequence returns a string without html tags so, once you have set the value, the next time you will get a string without html tags, and therefore you cannot track your previous html edits.
Other than this I have tried Typeface but even that didn't work out.
Also apologies if the work that I tried is not quite understandable, Its a part of a large code so there are quite a lot linked up and I tried to remove as much dependencies as I could.
You will want to use SpannableString:
String yourString = "The weather is nice today."
SpannableString contentSpan = new SpannableString(yourString);
contentSpan.setSpan(new TextAppearanceSpan(activity, R.style.bold_style), weatherFirstPos, weatherLastPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
contentSpan.setSpan(new TextAppearanceSpan(activity, R.style.italic_style), niceFirstPos, niceLastPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editTextcurrrent.setText(contentSpan, TextView.BufferType.SPANNABLE);
For R.style.bold_style and italic_style you can have something like:
<style name="bold_style">
<item name="android:textStyle">bold</item>
<item name="android:textColor">#color/black</item>
</style>
weatherFirstPos, weatherLastPos, niceFirstPos and niceLastPos are the positions of where you want to apply the style:
int weatherFirstPos = yourString.indexOf("weather");
int weatherLastPos = weatherFirstPos + "weather".length();
Use OnFocusChange Listener & Change EditText properties as you like when EditText gain focus of user
or
you can also set in Xml bold and italic.
<EditText
android:id="#+id/edittext"
android:layout_margin="#dimen/activity_horizontal_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:text="enter your name"/>

How do you change text to bold in Android?

How do you change text/font settings in an Android TextView?
For example, how do you make the text bold?
To do this in the layout.xml file:
android:textStyle
Examples:
android:textStyle="bold|italic"
Programmatically the method is:
setTypeface(Typeface tf)
Sets the typeface and style in which the text should be displayed. Note that not all Typeface families actually have bold and italic variants, so you may need to use setTypeface(Typeface, int) to get the appearance that you actually want.
Here is the solution
TextView questionValue = (TextView) findViewById(R.layout.TextView01);
questionValue.setTypeface(null, Typeface.BOLD);
Simply you can do the following:
Set the attribute in XML
android:textStyle="bold"
Programatically the method is:
TextView Tv = (TextView) findViewById(R.id.TextView);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
Tv.setTypeface(boldTypeface);
Hope this helps you thank you.
In XML
android:textStyle="bold" //only bold
android:textStyle="italic" //only italic
android:textStyle="bold|italic" //bold & italic
You can only use specific fonts sans, serif & monospace via xml, Java code can use custom fonts
android:typeface="monospace" // or sans or serif
Programmatically (Java code)
TextView textView = (TextView) findViewById(R.id.TextView1);
textView.setTypeface(Typeface.SANS_SERIF); //only font style
textView.setTypeface(null,Typeface.BOLD); //only text style(only bold)
textView.setTypeface(null,Typeface.BOLD_ITALIC); //only text style(bold & italic)
textView.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD);
//font style & text style(only bold)
textView.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD_ITALIC);
//font style & text style(bold & italic)
From the XML you can set the textStyle to bold as below
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bold text"
android:textStyle="bold"/>
You can set the TextView to bold programmatically as below
textview.setTypeface(Typeface.DEFAULT_BOLD);
For case where you are using custom fonts, but do not have bold typeface for the font you can use:
myTextView.setText(Html.fromHtml("<b>" + myText + "</b>");
Set the attribute
android:textStyle="bold"
It's very easy
setTypeface(Typeface.DEFAULT_BOLD);
If you're drawing it then this will do it:
TextPaint.setFlags(Paint.FAKE_BOLD_TEXT_FLAG);
In the ideal world you would set the text style attribute in you layout XML definition like that:
<TextView
android:id="#+id/TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"/>
There is a simple way to achieve the same result dynamically in your code by using setTypeface method. You need to pass and object of Typeface class, which will describe the font style for that TextView. So to achieve the same result as with the XML definition above you can do the following:
TextView Tv = (TextView) findViewById(R.id.TextView);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
Tv.setTypeface(boldTypeface);
The first line will create the object form predefined style (in this case Typeface.BOLD, but there are many more predefined). Once we have an instance of typeface we can set it on the TextView. And that's it our content will be displayed on the style we defined.
I hope it helps you a lot.For better info you can visit
http://developer.android.com/reference/android/graphics/Typeface.html
Through XML:
android:textStyle="bold"
Through Java:
//Let's say you have a textview
textview.setTypeface(null, Typeface.BOLD);
Define a new style with the format you want in the style.xml file in the values folder
<style name="TextViewStyle" parent="AppBaseTheme">
<item name="android:textStyle">bold</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">16sp</item>
<item name="android:textColor">#5EADED</item>
</style>
Then apply this style to the TextView by writing the following code with the properties of the TextView
style="#style/TextViewStyle"
The best way to go is:
TextView tv = findViewById(R.id.textView);
tv.setTypeface(Typeface.DEFAULT_BOLD);
in file .xml, set
android:textStyle="bold"
will set text type is bold.
4 ways to make Android TextView bold- Full answer is here.
Using android:textStyle attribute
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXTVIEW 1"
android:textStyle="bold"
/>
Use bold|italic for bold and italic.
using setTypeface() method
textview2.setTypeface(null, Typeface.BOLD);
textview2.setText("TEXTVIEW 2");
HtmlCompat.fromHtml() method, Html.fromHtml() was deprecated in API level 24.
String html="This is <b>TEXTVIEW 3</b>";
textview3.setText(HtmlCompat.fromHtml(html,Typeface.BOLD));
Assuming you are a new starter on Android Studio,
Simply you can get it done in design view XML by using
android:textStyle="bold" //to make text bold
android:textStyle="italic" //to make text italic
android:textStyle="bold|italic" //to make text bold & italic
You can use this for font
create a Class Name TypefaceTextView and extend the TextView
private static Map mTypefaces;
public TypefaceTextView(final Context context) {
this(context, null);
}
public TypefaceTextView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public TypefaceTextView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
if (mTypefaces == null) {
mTypefaces = new HashMap<String, Typeface>();
}
if (this.isInEditMode()) {
return;
}
final TypedArray array = context.obtainStyledAttributes(attrs, styleable.TypefaceTextView);
if (array != null) {
final String typefaceAssetPath = array.getString(
R.styleable.TypefaceTextView_customTypeface);
if (typefaceAssetPath != null) {
Typeface typeface = null;
if (mTypefaces.containsKey(typefaceAssetPath)) {
typeface = mTypefaces.get(typefaceAssetPath);
} else {
AssetManager assets = context.getAssets();
typeface = Typeface.createFromAsset(assets, typefaceAssetPath);
mTypefaces.put(typefaceAssetPath, typeface);
}
setTypeface(typeface);
}
array.recycle();
}
}
paste the font in the fonts folder created in the asset folder
<packagename.TypefaceTextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.5"
android:gravity="center"
android:text="TRENDING TURFS"
android:textColor="#000"
android:textSize="20sp"
app:customTypeface="fonts/pompiere.ttf" />**here pompiere.ttf is the font name**
Place the lines in the parent layout in the xml
xmlns:app="http://schemas.android.com/apk/res/com.mediasters.wheresmyturf"
xmlns:custom="http://schemas.android.com/apk/res-auto"
In my case, Passing value through string.xml worked out with html Tag..
<string name="your_string_tag"> <b> your_text </b></string>
editText.setTypeface(Typeface.createFromAsset(getAssets(), ttfFilePath));
etitText.setTypeface(et.getTypeface(), Typeface.BOLD);
will set both typface as well as style to Bold.
In Kotlin we can do in one line
TEXT_VIEW_ID.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
You can do this
ty.setTypeface(Typeface.createFromAsset(ctx.getAssets(), "fonts/magistral.ttf"), Typeface.BOLD);
textView.setPaintFlags(textView.getPaintFlags() | Paint.FAKE_BOLD_TEXT_FLAG)
To remove, use
textView.setPaintFlags(textView.getPaintFlags() & ~Paint.FAKE_BOLD_TEXT_FLAG)
Or in Kotlin:
fun TextView.makeBold() {
this.paintFlags = this.paintFlags or Paint.FAKE_BOLD_TEXT_FLAG
}
fun TextView.removeBold() {
this.paintFlags = this.paintFlags and (Paint.FAKE_BOLD_TEXT_FLAG.inv())
}

Categories

Resources