I have set android:inputType="text|textCapWords" to my EditText. When I type something in the field, the first letter is correctly capitalised, but if I set a full capitalised (or full lowercase) text using the setText() method, the text remains fully capitalised (or in lowercase).
How can I use setText for the text to comply with the input type?
As #Amarok suggests
This is expected behavior. You have to format the text yourself before
using the setText() method
But if you want to format your text just like android:inputType="text|textCapWords you can use the following method:
public static String modifiedLowerCase(String str){
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
for (String s : strArray) {
String cap = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
builder.append(cap + " ");
}
return builder.toString();
}
and use it like
textView.setText(modifiedLowerCase("hEllo worLd"));
It will convert it like :
Hello World
You can check for your editText Type constants, and add simple .toUpperCase() to the text you're adding, like this:
if(mEditText.getInputType() == TYPE_TEXT_FLAG_CAP_CHARACTERS+ TYPE_CLASS_TEXT)
mEditText.setText("Some text".toUpperCase());
else
mEditText.setText("some text");
More for input types constants can be found here
Use this
EditText.getText().clear();
EditText.getText().append("test");
rather than
EditText.setText("test");
so that the text that has been set follows the input type behavior
if (Global.DigsSinceLogin > 3) {
int a = Global.DigsSinceLogin;
noCoachingPoints.setText("Excellent Job! \n No Coaching Points Triggered in the Last "+ a +" Digs");}
Requirement:
Need to display value of "a" as 1)bold and 2)yellow color.
Is there a way i can display this value with the above changes and display in the same position
Try Below Code
if (Global.DigsSinceLogin > 3) {
int a = Global.DigsSinceLogin;
noCoachingPoints.setText(Html.fromHtml("Excellent Job!"+"<br>"+" No Coaching Points Triggered in the Last "+ "<font color=yellow><B>" + a + "</B></font>"+" Digs"));}
You can use a SpannableString or SpannableStringBuilder and apply both a StyleSpan and a ForegroundColorSpan to the text that needs special treatment. This much is pretty straightforward; I think the more difficult part will be finding the proper index of the character(s) in the string, especially when you start using localized string resources (which you should).
This is the string which i am getting from web using json api in my code:
String content = "<strong><em>India is the world’s hub for child sex trafficking</em>
</strong></p>\n<p style=\"text-align: center;\"><strong><em>Nearly 40,000 children are
abducted every year… </em></strong></p>\n<p style=\"text-align: center;\"><strong<em>
Every8 minutes a girl child goes missing in India!</em></strong></p>\n<p><strong>Priti
Pathak</strong></p>\n<p>MEET Shivani Shivaji Roy, Senior Inspector, Crime Branch, Mumbai
Police, as she sets out to confront the mastermind behind the child trafficking mafia,"
In this string whatever the text is in
"<strong><em> TEXT </em></strong>"
I want to display it BOLD. So for the above string
<strong><em>India is the world’s hub for child sex trafficking</em></strong>
will be displayed as
India is the world’s hub for child sex trafficking
. This should happen for entire string. This is the code which i am using:
int startIndex = content.indexOf("<strong><em>")+13; // 13 because <strong><em> has 13 characters
String substring = content.substring(startIndex, startIndex+200);
int subendIndex = substring.indexOf("</em></strong>");
int endIndex = startIndex + subendIndex;
SpannableString s = new SpannableString(content);
s.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), startIndex, endIndex, 0);
textview.setText(s, BufferType.SPANNABLE );
This code is working but it is setting bold text only to the text whichever is first within strong tag and not to the rest. Because I am setting bold text only to the first tag.
How should i get the startIndex, endIndex of all the "strong tags" and so i can set
s.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), startIndex, endIndex, 0);
to all the texts and also the number of times i would have to set the span.
I though of using regex also but i dont know how to get indexes using it. Any help would be nice. Thankyou !
The easier way is to use the Html class:
s = Html.fromHtml(content);
See the documentation for the details.
This is the simple way
TextView TV = (TextView)findViewById(R.id.Tv);
String Title="I N <big>D</big> I A";
TV.setText(Html.fromHtml(Title));
If you want to only bold some strings then I recommend Html.fromHtml. A short sample:
String str = "<b> bold text</b> unbold one";
textView.setText(Html.fromHtml(str));
Here's a list of html tags supported by textview.
Use regular HTML tags in Strings, This text uses bold and italics by using inline tags such as within the string file.. Refer this link Hope this Link would be helpful for you!
I have set a SpannableString to an EditText, now I want to get this text from the EditText and get its markup information. I tried like this:
SpannableStringBuilder spanStr = (SpannableStringBuilder) et.getText();
int boldIndex = spanStr.getSpanStart(new StyleSpan(Typeface.BOLD));
int italicIndex = spanStr.getSpanStart(new StyleSpan(Typeface.ITALIC));
But it gives index -1 for both bold and italic, although it is showing text with italic and bold.
Please help.
From the code you've posted, you're passing new spans to spanStr and asking it to find them. You'll need to have a reference to the instances of those spans that are actually applied. If that's not feasible or you don't want to track spans directly, you can simply call
getSpans to get all the spans applied. You can then filter that array for what you want.
If you don't care about the spans in particular, you can also just call Html.toHtml(spanStr) to get an HTML tagged version.
edit: to add code example
This will grab all applied StyleSpans which is what you want.
/* From the Android docs on StyleSpan: "Describes a style in a span.
* Note that styles are cumulative -- both bold and italic are set in
* separate spans, or if the base is bold and a span calls for italic,
* you get bold italic. You can't turn off a style from the base style."*/
StyleSpan[] mSpans = et.getText().getSpans(0, et.length(), StyleSpan.class);
Here's a link to the StyleSpan docs.
To pick out the spans you want if you have various spans mixed in to a collection/array, you can use instanceof to figure out what type of spans you've got. This snippet will check if a particular span mSpan is an instance of StyleSpan and then print its start/end indices and flags. The flags are constants that describe how the span ends behave such as: Do they include and apply styling to the text at the start/end indices or only to text input at an index inside the start/end range).
if (mSpan instanceof StyleSpan) {
int start = et.getSpanStart(mSpan);
int end = et.getSpanEnd(mSpan);
int flag = et.getSpanFlags(mSpan);
Log.i("SpannableString Spans", "Found StyleSpan at:\n" +
"Start: " + start +
"\n End: " + end +
"\n Flag(s): " + flag);
}
A ListView in my application has many string elements like name, experience, date of joining, etc. I just want to make name bold. All the string elements will be in a single TextView.
my XML:
<ImageView
android:id="#+id/logo"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/logo"
android:padding="5dp"
android:textSize="12dp" >
</TextView>
My code to set the TextView of the ListView item:
holder.text.setText(name + "\n" + expirience + " " + dateOfJoininf);
Let's say you have a TextView called etx. You would then use the following code:
final SpannableStringBuilder sb = new SpannableStringBuilder("HELLOO");
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
final StyleSpan iss = new StyleSpan(android.graphics.Typeface.ITALIC); //Span to make text italic
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
sb.setSpan(iss, 4, 6, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make last 2 characters Italic
etx.setText(sb);
Based on Imran Rana's answer, here is a generic, reusable method if you need to apply StyleSpans to several TextViews, with support for multiple languages (where indices are variable):
void setTextWithSpan(TextView textView, String text, String spanText, StyleSpan style) {
SpannableStringBuilder sb = new SpannableStringBuilder(text);
int start = text.indexOf(spanText);
int end = start + spanText.length();
sb.setSpan(style, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(sb);
}
Use it in an Activity like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
StyleSpan boldStyle = new StyleSpan(Typeface.BOLD);
setTextWithSpan((TextView) findViewById(R.id.welcome_text),
getString(R.string.welcome_text),
getString(R.string.welcome_text_bold),
boldStyle);
// ...
}
strings.xml
<string name="welcome_text">Welcome to CompanyName</string>
<string name="welcome_text_bold">CompanyName</string>
Result:
Welcome to CompanyName
You can do it using Kotlin and buildSpannedString extension function from core-ktx
holder.textView.text = buildSpannedString {
bold { append("$name\n") }
append("$experience $dateOfJoining")
}
The answers provided here are correct, but can't be called in a loop because the StyleSpan object is a single contiguous span (not a style that can be applied to multiple spans). Calling setSpan multiple times with the same bold StyleSpan would create one bold span and just move it around in the parent span.
In my case (displaying search results), I needed to make all instances of all the search keywords appear bold. This is what I did:
private static SpannableStringBuilder emboldenKeywords(final String text,
final String[] searchKeywords) {
// searching in the lower case text to make sure we catch all cases
final String loweredMasterText = text.toLowerCase(Locale.ENGLISH);
final SpannableStringBuilder span = new SpannableStringBuilder(text);
// for each keyword
for (final String keyword : searchKeywords) {
// lower the keyword to catch both lower and upper case chars
final String loweredKeyword = keyword.toLowerCase(Locale.ENGLISH);
// start at the beginning of the master text
int offset = 0;
int start;
final int len = keyword.length(); // let's calculate this outside the 'while'
while ((start = loweredMasterText.indexOf(loweredKeyword, offset)) >= 0) {
// make it bold
span.setSpan(new StyleSpan(Typeface.BOLD), start, start+len, SPAN_INCLUSIVE_INCLUSIVE);
// move your offset pointer
offset = start + len;
}
}
// put it in your TextView and smoke it!
return span;
}
Keep in mind that the code above isn't smart enough to skip double-bolding if one keyword is a substring of the other. For example, if you search for "Fish fi" inside "Fishes in the fisty Sea" it will make the "fish" bold once and then the "fi" portion. The good thing is that while inefficient and a bit undesirable, it won't have a visual drawback as your displayed result will still look like
Fishes in the fisty Sea
if you don't know exactly the length of the text before the text portion that you want to make Bold, or even you don't know the length of the text to be Bold, you can easily use HTML tags like the following:
yourTextView.setText(Html.fromHtml("text before " + "<font><b>" + "text to be Bold" + "</b></font>" + " text after"));
<string name="My_Name">Given name is <b>Not Right</b>Please try again </string>
use "b" tag in string.xml file.
also for Italic "i" and Underline "u".
Extending frieder's answer to support case and diacritics insensitivity.
public static String stripDiacritics(String s) {
s = Normalizer.normalize(s, Normalizer.Form.NFD);
s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
return s;
}
public static void setTextWithSpan(TextView textView, String text, String spanText, StyleSpan style, boolean caseDiacriticsInsensitive) {
SpannableStringBuilder sb = new SpannableStringBuilder(text);
int start;
if (caseDiacriticsInsensitive) {
start = stripDiacritics(text).toLowerCase(Locale.US).indexOf(stripDiacritics(spanText).toLowerCase(Locale.US));
} else {
start = text.indexOf(spanText);
}
int end = start + spanText.length();
if (start > -1)
sb.setSpan(style, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(sb);
}
If you are using the # srings / your_string annotation, access the strings.xml file and use the <b></b> tag in the part of the text you want.
Example:
<string><b>Bold Text</b><i>italic</i>Normal Text</string>
I recommend to use strings.xml file with CDATA
<string name="mystring"><![CDATA[ <b>Hello</b> <i>World</i> ]]></string>
Then in the java file :
TextView myTextView = (TextView) this.findViewById(R.id.myTextView);
myTextView.setText(Html.fromHtml( getResources().getString(R.string.mystring) ));
To better support translations and remove any dependency on length of the string or particular index, you should use android.text.Annotation in you string defined strings.xml.
In your particular case, you can create a string like below
<string name="bold_name_experience_text"><annotation type="bold">name</annotation> \nexpirience dateOfJoininf</string>
or if you want to substitute these in runtime, you can create a string as follow
<string name="bold_name_experience_text"><annotation type="bold">name</annotation> \n%d %s</string>
You must apply this bold_name_experience_text in your text view label. These annotation class spans get added to your string and then you can iterate on them to apply the bold span.
You can refer to my SO answer which shows the Kotlin code to iterate through these spans and apply the bold span
Remember all the above answers has one of the following flows:
They are using some hard-coded index logic which may crash or give wrong results in some other language
They are using hardcode string in Java code which will result in lots of complicated logic to maintain internalisation
Some used Html.fromHtml which can be acceptable answer depending on the use-case. As Html.fromHtml doesn't always work for all types of HTML attributes for example there is not support of click span. Also depending on OEM you might get different rendered TextView