Now I am writing simple note app. And i need to display formatted separate selected text in EditText.
I tried,
EditText et = (EditText)findViewById(R.id.edittext);
String string;
int startSelection = et.getSelectionStart();
int endSelection = et.getSelectionEnd();
string = et.getText().toString();
string.substring(startSelection, endSelection);
Spanned s = Html.fromHtml("<font color=\"red\">" + string + "</font>");
et.setText(s);
This solution displays only separate selected text. But i need to display formatted text among other text. I have no idea.
UPD: Formatting happening, when user clicks on the button.
Try this
EditText text = new EditText(this);
text.setText(Html.fromHtml(html));
text.setMovementMethod(LinkMovementMethod.getInstance());
try using this
String string = et.getText().toString();
String selectedString = string.substring(startSelection, endSelection);
Spanned s = Html.fromHtml(string.replace(selectedString, "<font color=\"red\">" + selectedString + "</font>"));
If you talking about formatting the Text, You can always do like this
EditText et = new EditText(this);
et.setText(Html.fromHtml("Simple Text <B>Formatted Text</B> Simple Text Again"));
And If you want to linkify a specific part of the Text then do it like this using this Blog
EditText mTextSample = new EditText(this);
String text = "click to see stackoverflow.com here";
mTextSample.setText(text);
Pattern pattern = Pattern.compile("stackoverflow.com");
Linkify.addLinks(mTextSample, pattern, "http://");
Related
I try to put one or more variables in a TextView.
For exemple :
Hello I am a "girl" and I live in "Boston"
I would like to know what is the best way to do it :
Can i do it directly in the layout file ?
Can i do it only via Java Class ?
Can i do it via values/styles.xml ?
For now i do it like this :
String text1 = "Hello I am a ";
String text2 =" and I live in ";
String var1= preferences.getString("sex", "null");
String var2= preferences.getString("city", "null");
TextView Text = (TextView) findViewById(R.id.text);
Text.setText(text1 + var1 + text2 + var2);
It works yes but in fact my TextView are very long so I don't think my way is really appropriate.
Can i have some advice ?
Use String.format(String format, Object... args)
String sex = preferences.getString("sex", "null");
String city = preferences.getString("city", "null");
String str = String.format("Hello I am a %s and I live in %s", sex, city);
TextView text = (TextView) findViewById(R.id.text);
text.setText(str);
Note - Avoid concatenation in TextView.setText()
If Text-view is really long then you should be try this.
String var1= preferences.getString("sex", "null");
String var2= preferences.getString("city", "null");
Text.setText("Hello I am a"+var1+"\n"+"I live in"+var2);
This is good way Present Text in Text View
I have to develop an App like sticky note. User enter the text in Edittext, while selecting the text I will open the popup to select the option like (BOLD,ITALIC,UNDERLINE). when user select the options i need to change the selected text..
Does anyone go through this?
If you have found a way the popup the options and how to retrieve the selected option(Bold, Italics, Underline), Then use this to format the text
private void formatText(EditText editText) {
int end = editText.length();
//get the selected text position as integer
start = editText.getSelectionStart();
stop = editText.getSelectionEnd();
//check if the user started the selection from the left or the right
if (start > stop) {
stop = editText.getSelectionStart();
start = editText.getSelectionEnd();
}
//gets the texts as html incase if previous formatting exists
String textBefore = Html.toHtml(new SpannableString(text.getText().subSequence(0, start)));
String selectedText = Html.toHtml(new SpannableString(text.getText().subSequence(start, stop)));
String textAfter = Html.toHtml(new SpannableString(text.getText().subSequence(stop, end)));
//Check if the selected text is empty ie if the did not select anything
if (!selectedText.equals("") || start != stop) {
//format the text
String formatted = "<b>" + selectedText + "</b>";
//build back the text
StringBuilder builder = new StringBuilder();
builder.append(textBefore);
builder.append(Html.toHtml(formatted));
builder.append(textAfter);
editText.setText(Html.fromHtml(builder.toString()));
//make the cursor stay after the selected text
//you can also make the selected text selected here
editText.setSelection(stop);
//clear your local variables
textbefore = "";
textafter = "";
selectedText = "";
}
else {
//you can also use snack bar here
Toast.makeText(context, "select a text", Toast.LENGTH_SHORT).show();
}
}
I think this should work for you
Kotlin
Change Typeface.BOLD, Typeface.ITALIC or UnderlineSpan()
val spannableString: Spannable = SpannableStringBuilder(editText.text)
spannableString.setSpan(
StyleSpan(Typeface.BOLD),
editText.selectionStart,
editText.selectionEnd,
0
)
editText.setText(spannableString)
Did you try this?
editText.setTypeface(null, Typeface.BOLD_ITALIC);
editText.setTypeface(null, Typeface.BOLD);
editText.setTypeface(null, Typeface.ITALIC);
editText.setTypeface(null, Typeface.NORMAL);
I am unable to get text in an AlertDialog to display in bold or italic.
I've tried formatting directly and also using the CharSequence utilties from the Android string-resource page but I always get just plain text.
What am I doing wrong?
MyFragment.java
String idFormatted = String.format(resources.getString(R.string.id));
CharSequence idStyledText = Html.fromHtml(idFormatted);
CharSequence nameItalic = Utilities.italic(resources.getString(R.string.name));
String typeFormatted = String.format(resources.getString(R.string.type));
CharSequence typeStyledText = Html.fromHtml(idFormatted);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setPositiveButton("Dismiss",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setIcon(android.R.drawable.ic_dialog_info);
builder.setMessage( idFormatted + myData.getId() + "\t\t" + nameItalic + myData.getName() + "\t\t" + typeFormatted + myData.getType() );
Dialog dialog = builder.create();
dialog.setTitle("Details");
dialog.show();
strings.xml
<string name="id"><i>Id: </i></string>
<string name="name"><i>Name: </i></string>
<string name="type"><i>Type: </i></string>
Edit: -------------------------------------------------------------
Mohammad Arman suggests that the strings from the string.xml will not retain the html. This seems likely to be true, though I can't prove it yet.
Based on his and Farbod Salamat-Zadeh's answer, I tried the code below, but still the result is the same, just plain text.
Spanned idLabel = Html.fromHtml("<i>" + resources.getString(R.string.id) + "</i>");
Spanned nameLabel = Html.fromHtml("<i>" + resources.getString(R.string.name) + "</i>");
Spanned typeLabel = Html.fromHtml("<i>" + resources.getString(R.string.type) + "</i>");
...
builder.setMessage(idLabel.toString() + myData.getId() + "\t\t" + nameLabel + myData.getName());
Edit2: -----------------------------------------------------------
I've tried as Keelan has suggested:
<string name="italic_string"><![CDATA[<i>italic-string</i>]]></string>
and then:
String formattedText = getString(R.string.italic_string);
Spanned result = Html.fromHtml(formattedText);
builder.setMessage(result);
This works.
You can't simply store HTML in a strings.xml file. You need to put them in CDATA, like so:
<string name="id"><![CDATA[<i>Id: </i>]]></string>
Then to display a formatted string, you still need to use Html.fromHtml().
You can get text anywhere to display in bold or italic - I use the following;
Spanned italicText = Html.fromHtml("<i>" + "My italic text" + "</i>");
Spanned boldText = Html.fromHtml("<b>" + "My boldtext" + "</b>");
// You can use different HTML tags depending on what you want.
You need to format the html version in a separate String variable in Java class (otherwise for some reason it won't work).
String myId = <i>Id: </i>;
String myName = <b>Name: </b>
Then you have to add this in the textView like bellow:
textView1.setText(Html.fromHtml(myId +" "+ "1234");
textView2.setText(Html.fromHtml(myName +" "+ "Al Lelopath")
Why your approach is not working
It's because as you are importing the string from string.xml it will lose the attribute and send it as a plain text. And that's why Android could not take that as html.
I have a textview that should be in all caps and mark any urls found in it with a specific color, so naturaly I've tried textColorLink, with the option textAllCaps="true", however the url is not colored, my guess is that the regex does not match uppercase urls, since the url is colored if the same text is in lowercase.
I've tried solving it with this:
Spannable formatted = new SpannableString(text);
Pattern url = Pattern.compile(
"(https?)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]");
Matcher matcher = url.matcher(text.toLowerCase());
while (matcher.find())
{
Log.e("TEST",matcher.group());
int begIndex = matcher.start();
int endIdx = begIndex + matcher.group().length() - 1;
Log.e("Found", String.valueOf(begIndex));
formatted.setSpan(new ForegroundColorSpan(
getResources().getColor(android.R.color.holo_red_light)),
begIndex, endIdx, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
mTextView.setText(formatted);
Apparently it finds the text, however once again it is not colored. I've been at this for hours, how do you solve this?
when you try to upperCase the string lose the color but if you add another SpannableString and pass to this the string.toUpperCase than you can setSpan...
SpannableString formatted = new SpannableString(urlString);
Pattern url = Pattern.compile("(https?)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]");
Matcher matcher = url.matcher(urlString.toLowerCase());
//Here you save the string in upper case
SpannableString stringUpperCase = new SpannableString(formatted.toString().toUpperCase());
while (matcher.find()) {
int begIndex = matcher.start();
int endIdx = begIndex + matcher.group().length() - 1;
stringUpperCase.setSpan(new ForegroundColorSpan(R.color.Red),
0, formatted.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
TextView text = (TextView) findViewById(R.id.textView);
text.setText(string);
Should works...
Remove from xml the textAllCaps="true"
I have set a Bold Span to some specific words in an EditText, now i want to get these words from EditText and add them into a list.
How can i be able to find what words are bold and add them to the list?
You can do it like this.
EditText t /* assign EditText instance */
Editable text = t.getText();
StyleSpan[] spans = text.getSpans(0 , text.length(), StyleSpan.class);
ArrayList<CharSequence> list = new ArrayList<CharSequence>(10);
for (StyleSpan s : spans){
if (s.getStyle() == android.graphics.Typeface.BOLD){
int start = text.getSpanStart(s);
int end = text.getSpanEnd(s);
CharSequence cs = text.subSequence(start, end+1);
list.add(cs);
}
}