Related
I would programmatically like to create a button as defined in the design guidelines here: https://material.io/design/components/buttons.html#outlined-button, looking like this:
In XML I'm able to do this, using this piece of layout xml:
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonGetStarted"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"
android:text="#string/title_short_intro" />
What I'm looking for is an example that shows how to do this using Java code? I have tried the following:
MaterialButton testSignIn = new MaterialButton( new ContextThemeWrapper( this, R.style.Widget_MaterialComponents_Button_OutlinedButton));
String buttonText = "Sign-in & empty test account";
testSignIn.setText( buttonText );
But this does not result in the outline variant:
You can use below:
MaterialButton testSignIn = new MaterialButton(context, null, R.attr.borderlessButtonStyle);
String buttonText = "Sign-in & empty test account";
testSignIn.setText(buttonText);
If you want to apply a Outlined button you can use the R.attr.materialButtonOutlinedStyle attribute style in the constructor:
MaterialButton outlinedButton = new MaterialButton(context,null, R.attr.materialButtonOutlinedStyle);
outlinedButton.setText("....");
MaterialButton has strokeColor and strokeWidth which is used to set the outline.
val _strokeColor = getColorStateList(R.styleable.xxx_strokeColor)
val _strokeWidth = getDimensionPixelSize(R.styleable.xxx_strokeWidth, 0)
button = MaterialButton(context).apply {
layoutParams = LayoutParams(MATCH_PARENT, WRAP_PARENT)
strokeColor = _strokeColor
strokeWidth = _strokeWidth
}
Create outlined button layout outlined_button.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.button.MaterialButton xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.google.android.material.button.MaterialButton>
Then inflate outlined button in runtime
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MaterialButton button = (MaterialButton)inflater.inflate(R.layout.outlined_button, vg, false);
My goal to hide text and keep textview occupying its space in the activity , i set already my text to be invisible by using :
tv.setVisibility(View.INVISIBLE);
and when button clicked it show the text , every thing work fine except the result of my code lead to hide whole textview not only the text , because i set my textview background to drawable shape which form red border around the text as:
android:background="#drawable/border1"
<TextView
android:id="#+id/introclusion_tv3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/border1"
android:textSize="20sp" />
when start app you can see empty space only which will be fill with text after button click but there's no border there (which come from shape background) , so it hide whole textview and i need it to hide only text and keep the textview with its background shown when text set to INVISIBLE,
any help will be really appreciated ,thanks.
this is how i did it:
TextView tv11=(TextView)findViewById(R.id.introclusion_tv3);
tv11.setText(Html.fromHtml(getString(R.string.introclusion_one)));
tv11.setVisibility(View.INVISIBLE);
then after click the but and write correct password it show the text as:
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
EditText password = (EditText) dialog.findViewById(R.id.password);
if( password.getText().toString().length() > 0 ) {
if( password.getText().toString().equals("test")) {
TextView tv11=(TextView)findViewById(R.id.introclusion_tv3);
tv11.setTypeface(FontFactory.getBFantezy(getBaseContext()));
tv11.setText(Html.fromHtml(getString(R.string.introclusion_one)));
tv11.setVisibility(View.VISIBLE);
}
Transparent text color hides the text:
<TextView
android:id="#+id/introclusion_tv3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/border1"
android:textColor="#android:color/transparent"
android:textSize="20sp" />
When you want to show your text, change the text color programmatically using method setTextColor():
tv11.setTextColor(color);
// try this way
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/border1">
<TextView
android:id="#+id/introclusion_tv3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
</LinearLayout>
you can make simple trick : write two string
lets say in your first and second piece of code just remove this line
tv11.setVisibility(View.INVISIBLE);
and
tv11.setVisibility(View.VISIBLE);
so it will be
TextView tv11=(TextView)findViewById(R.id.introclusion_tv3);
tv11.setText(Html.fromHtml(getString(R.string.introclusion_one)));
then in second piece write as follow ;
if( password.getText().toString().equals("test")) {
TextView tv11=(TextView)findViewById(R.id.introclusion_tv3);
tv11.setTypeface(FontFactory.getBFantezy(getBaseContext()));
tv11.setText(Html.fromHtml(getString(R.string.introclusion_one_appear)));
}
where first string will be empty
<string name="introclusion_one">
and second string you will write your text in it
<string name="introclusion_one_appear">
Hope help you .
save what is in the text view as a string like this:
String x = (String)tv11.getText();
then make the text view empty like this:
String x = "";
for(int i = 0; i < x.length(); i++){
x +=" ";
}
tv11.setText(x);
to make the textview visible again do:
tv11.setText(x);
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())
}
I want to make a TextView's content bold, italic and underlined. I tried the following code and it works, but doesn't underline.
<Textview android:textStyle="bold|italic" ..
How do I do it? Any quick ideas?
This should make your TextView bold, underlined and italic at the same time.
strings.xml
<resources>
<string name="register"><u><b><i>Copyright</i></b></u></string>
</resources>
To set this String to your TextView, do this in your main.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/register" />
or In JAVA,
TextView textView = new TextView(this);
textView.setText(R.string.register);
Sometimes the above approach will not be helpful when you might have to use Dynamic Text. So in that case SpannableString comes into action.
String tempString="Copyright";
TextView text=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
text.setText(spanString);
OUTPUT
I don't know about underline, but for bold and italic there is "bolditalic". There is no mention of underline here: http://developer.android.com/reference/android/widget/TextView.html#attr_android:textStyle
Mind you that to use the mentioned bolditalic you need to, and I quote from that page
Must be one or more (separated by '|') of the following constant values.
so you'd use bold|italic
You could check this question for underline: Can I underline text in an android layout?
Or just like this in Kotlin:
val tv = findViewById(R.id.textViewOne) as TextView
tv.setTypeface(null, Typeface.BOLD_ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD or Typeface.ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD)
// OR
tv.setTypeface(null, Typeface.ITALIC)
// AND
tv.paintFlags = tv.paintFlags or Paint.UNDERLINE_TEXT_FLAG
Or in Java:
TextView tv = (TextView)findViewById(R.id.textViewOne);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD|Typeface.ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD);
// OR
tv.setTypeface(null, Typeface.ITALIC);
// AND
tv.setPaintFlags(tv.getPaintFlags()|Paint.UNDERLINE_TEXT_FLAG);
Keep it simple and in one line :)
For bold and italic whatever you are doing is correct for underscore use following code
HelloAndroid.java
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.widget.TextView;
public class HelloAndroid extends Activity {
TextView textview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview = (TextView)findViewById(R.id.textview);
SpannableString content = new SpannableString(getText(R.string.hello));
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
textview.setText(content);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/hello"
android:textStyle="bold|italic"/>
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, HelloAndroid!</string>
<string name="app_name">Hello, Android</string>
</resources>
This is an easy way to add an underline, while maintaining other settings:
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Programmatialy:
You can do programmatically using setTypeface() method:
Below is the code for default Typeface
textView.setTypeface(null, Typeface.NORMAL); // for Normal Text
textView.setTypeface(null, Typeface.BOLD); // for Bold only
textView.setTypeface(null, Typeface.ITALIC); // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic
and if you want to set custom Typeface:
textView.setTypeface(textView.getTypeface(), Typeface.NORMAL); // for Normal Text
textView.setTypeface(textView.getTypeface(), Typeface.BOLD); // for Bold only
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC); // for Italic
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); // for Bold and Italic
XML:
You can set Directly in XML file in like:
android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"
If you are reading that text from a file or from the network.
You can achieve it by adding HTML tags to your text like mentioned
This text is <i>italic</i> and <b>bold</b>
and <u>underlined</u> <b><i><u>bolditalicunderlined</u></b></i>
and then you can use the HTML class that processes HTML strings into displayable styled text.
// textString is the String after you retrieve it from the file
textView.setText(Html.fromHtml(textString));
Without quotes works for me:
<item name="android:textStyle">bold|italic</item>
You can achieve it easily by using Kotlin's buildSpannedString{} under its core-ktx dependency.
val formattedString = buildSpannedString {
append("Regular")
bold { append("Bold") }
italic { append("Italic") }
underline { append("Underline") }
bold { italic {append("Bold Italic")} }
}
textView.text = formattedString
Just one line of code in xml
android:textStyle="italic"
style="?android:attr/listSeparatorTextViewStyle
by making this style, u can achieve underlining
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.