Format text in AlertDialog.Builder - android

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.

Related

how to automatically make a text highlighted in android

in my android application the user can send feedback
public void c_send_send(View v) {
Uri uri = Uri.parse("mailto:xx#xx.net");
Intent send = new Intent(Intent.ACTION_SENDTO, uri);
send.putExtra(Intent.EXTRA_SUBJECT, "feedback");
send.putExtra(
Intent.EXTRA_TEXT,
DeviceInformation(getResources().getString(R.string.app_name),
getResources().getString(R.string.app_version)));
startActivity(Intent.createChooser(send, "feedback"));
}
public static String DeviceInformation(String app_name, String app_version) {
String EnterTextHere = "[Enter Text Here]";
Spannable spanText = Spannable.Factory.getInstance().newSpannable(EnterTextHere);
spanText.setSpan(new BackgroundColorSpan(0xFFFFFF00), 1, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
String info = "\n" + spanText + "\n\n\n\nDevice Model: "
+ android.os.Build.MANUFACTURER
+ " " + android.os.Build.MODEL + "\nAndroid Version: "
+ Build.VERSION.RELEASE + "\nApplication Version: "
+ app_version;
return info;
}
the question how can i make
[Enter Your Text Here]
highlighted as shown in the picture posted in the link below
Example
Spannable strings are a very good way to use different styling in a single string. try exploring its different functions.
You can make it highlighted by the Toast option in android
Toast.makeText(getApplicationContext(), (String)data.result, Toast.LENGTH_LONG).show();

How display formatted text in EditText?

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://");

Reference string resource from code

I have the following string declared in strings.xml:
<string name="last_msg">Your last click was on</string>
Now when someone clicks a button, I want a textview to show this string, with a space, then a variable value that is a timestamp.
Unfortunately, using #string/last_msg isn't working, and I'm not sure how to do this properly so I'm not hardcoding in content.
Here's my code for the onClick function:
public void showMsgNow(View view) {
TextView lastMsg = (TextView)findViewById(R.id.textView2);
long currentTimeStamp = System.currentTimeMillis();
lastMsg.setText(#string/last_msg + " " + currentTimeStamp);
}
I'm a newbie, any help would be great !
I found the answer on Google:
getString(R.string.last_msg)
you cant access String directly by #, for that you need to have context resource and then just do this...
lastMsg.setText(context.getResources().getString(R.string.last_msg) + " " + currentTimeStamp);
in your case use
<string name="last_msg">Your last click was on %1$s</string>
implementation:
public void showMsgNow(View view) {
TextView lastMsg = (TextView)findViewById(R.id.textView2);
long currentTimeStamp = System.currentTimeMillis();
lastMsg.setText(context.getResources()
.getString(R.string.last_msg, currentTimeStamp));
}
// getString is method of context
if (this instanceof Context)
//If you are in Activity or Service class
lastMsg.setText(getString(R.string.last_msg)+ " " + currentTimeStamp);
else
//you need to context to get the string
lastMsg.setText(getString(mContext,R.string.last_msg)+ " " + currentTimeStamp);
public String getString(Context mContext, int id){
return mContext.getResources().getString(id);
}
use below line
lastMsg.setText(getString(R.string.last_msg) + " " + currentTimeStamp);
Try this :
lastMsg.setText(R.string.last_msg + " " + new SimpleDateFormat(d-MM-YYYY).format(new Date()));

Android: How to append formatted text to android.text.Editable?

Within a TagHandler which I passed to Html.fromHtml(), I would like to append some formatted text to the given Editable output object, which then gets passed to a TextView.
Appending plain text with output.append("my text") works fine. But how to append red or italic text?
class MyTagHandler implements Html.TagHandler {
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
output.append("my text");
// how to append red and italic text here ?
}
}
You should be able to use Html.fromHtml and Editable.setSpan() to do it. Here's some sample code:
appendFormatted(output, "<font color=red><i>red italic</i></font>");
}
private void appendFormatted(Editable text, String string) {
final int start = text.length();
final Spanned span = Html.fromHtml(string);
text.append(span);
final int end = text.length();
for (final Object o : span.getSpans(0, span.length(), Object.class)) {
text.setSpan(o, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
If you just need some simple formatting applied, you can pass in the specific CharacterStyle derived-object to the Editable.setSpan() call - see the "Selecting, Highlighting, or Styling Portions of Text" example on the developers site.
If I understood your question right here is a way to do this
mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" + "<br />" +
"<small>" + description + "</small>" + "<br />" +
"<small>" + DateAdded + "</small>"));
The answer was copied from a similar question here.

How to display the value of string with its title using html format

I have same info String like...
String info1 ="yyy";
String info2 ="mmm";
Now I want to disply it in Html Format and bold As..
Our First Information:yyy
Our Second Information:mmm
Below is example for the same.
textview.setText(
Html.fromHtml(
"<b>" +info1 + "</b> " + "<font color=\"#000000\">" +
info2 +
"</font>"+
""));
String info1 ="yyy"; String info2 ="mmm";
etmsg.setText(Html.fromHtml("First Info <b>"+info1+"</b>"+"<br/>Second Info <b>"+info2+"</b>"));
assuming you're using a textview :
myTextView.setText(Html.fromHtml("<h2>"youString"</h2><br><p>"YourSecondString"</p>"));
First define your string in string.xml file which is under values folder in resources folder as:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="select"><b><h2>S</h2></b>elect</string>
</resources>
and then use them as
android:text="#string/select"...
String info1 ="yyy";
String info2 ="mmm";
TextView txt;
txt = (TextView)findViewById(R.id.txt);
txt.setText(Html.fromHtml("<b>" + str1 + "</b>" + "<br />" +
"<small>" + str2 + "</small>" ));
Just pointing out that a SpannableStringBuilder may be an interesting alternative if you're looking for a non-HTML-based solution. This way you could for example also use an inline HTML-styled link (URLSpan) to not execute the default ACTION_VIEW on the provided URL, but have it launch a new activity - or anything else you like.
String boldText = getString(R.string.bold_text);
String italicText = getString(R.string.italic_text);
String strikethroughText = getString(R.string.strikethrough_text);
String urlText = getString(R.string.url_text);
SpannableStringBuilder ssb = new SpannableStringBuilder();
ssb.append(boldText);
ssb.setSpan(new StyleSpan(Typeface.BOLD), ssb.length()-boldText.length(), ssb.length() , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.append(" ");
ssb.append(italicText);
ssb.setSpan(new StyleSpan(Typeface.ITALIC), ssb.length()-italicText.length(), ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.append(" ");
ssb.append(strikethroughText);
ssb.setSpan(new StrikethroughSpan(), ssb.length()-strikethroughText.length(), ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.append(" ");
ssb.append(urlText);
ssb.setSpan(new URLSpan("http://www.stackoverflow.com"), ssb.length()-urlText.length(), ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView tv = (TextView) findViewById(R.id.spannable_text);
tv.setText(ssb);
Which will look as follows:
Other spans can be found as subclass of CharacterStyle. E.g. the TextAppearanceSpan allows you to do most of the above but then by using xml-declared styles. I've used it to create a Button with two lines of text with different styles (different text size and colour) applied to each line.

Categories

Resources