Format a string with html elements in react native - android

I am trying to create a component to display some generic product info. The string is formatted by a CRM so it has HTML elements in it "<BR>, <b> </b> etc.
eg:
"<BR>Łosoś to<b> szlachetna ryba,</b> można z niej przyrządzać przepyszne dania główne, genialne przystawki, a także niezwykle smaczne pasztety i farsze. Doskonale nadaje się do<b> pieczenia, smażenia, duszenia i grillowania. <BR><BR>Trym D:</b> Usunięty kręgosłup, ości brzuszne, tylne płetwy, kość obojczyka, tłuszcz na płetwie brzusznej usunięty częściowo, usunięte ości, ścięty ogon, usunięta otrzewna.<BR>"
I want to format the string so it renders properly in react native.
I tried using ramda's replace and it worked for adding new lines /n however I do not think this will work for making the text bold.
is there some library that will format strings with html elements into a react native friendly format?

Related

Android/iOS keyboard: stickers API

I was searching for a way to create a custom keyboard to add custom emoji and stickers.
So far I've figured out that emoji are just unicode characters and in order to add custom emoji one should supply a custom font with the dedicated emoji mapped to a predefined unicode character inside the font. This font should be available across users of the app in order for the custom emoji to display correctly.
The question arises when it comes to stickers (those big images available to add for example in Facebook comments). I can't find any useful information on how they work and what is the interface to embed them in the custom keyboard and to paste further to a text. There are apps available on Google Play and AppStore that does it (like "Go Keyboard" app for example)
Can anyone point me in the right direction?
So the question is:
How to embed stickers into a text to share further to 3rd-party apps? My main idea is to understand if there is a common standard or API for stickers (like for emoji)? Or the only way to use stickers is to use/build a custom chat API with a backend server which means only apps that use the same service will reliably decode the shared text to display stickers correctly?
I've been working in an iOS project to prove this concept of using emojis and stickers in chat conversations.
You can check it out in my GitHub repository and contribute if you want (review and improvement are welcome).
What I done was, use the NSTextAttachment to attach an image within an UITextView, using the NSAttributedString object type.
To show a image as an emoji, within in an UITextView:
// initialize object with the content of textView
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithAttributedString:textview.attributedText];
// initialize selected image to be used as emoji
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:#"MicheyMouse"];
textAttachment.image = [UIImage imageWithCGImage:textAttachment.image.CGImage scale:25 orientation:UIImageOrientationUp];
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributeString appendAttributedString:attrStringWithImage];
// blank space after the image
NSAttributedString *blank = [[NSAttributedString alloc] initWithString:#" "];
[attributeString appendAttributedString:blank];
textview.attributedText = attributeString;
And if you wanna use the image as a sticker, follow this lines:
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:sticker];
textAttachment.image = [UIImage imageWithCGImage:textAttachment.image.CGImage scale:12 orientation:UIImageOrientationUp]; // --> change de scale, to change image size (or create the image in size that you want)
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
cell.textLabel.attributedText = attrStringWithImage
In this example, I attached the image as a sticker directly in a cell (you can do this cell as a chat ballon).
In other words, in the first code lines, I basically showed the image in an UITextView, and in the second I put the image directly in chat lines.
I had to do my own sticker/emoji keyboard and I also made some work to handle the switching between emoji keyboard and typing keyboard.
This is the GitHub repository for the project example: https://github.com/cairano/CIStickerFacilities

How to display source code "prettily" in android app

everyone.
[What I'd like to do]
To display source code "prettily" in android app. Like this.
At least if there are indents, it's fine.
[Why?]
Because I'm developing an android app where users can see Views and its source code at the same time.
[Issue]
Showing source codes on TextView looks ugly. A lot of escape characters needed for <> and the text layout collapsed. Googling and searching on Stackoverflow didn't give me any useful information.
Any help would be appreciated. Thanks!
(update 2015/11/23)
These link might be useful when you use WebView to display source codes.
- How can I display HTML source code within a HTML website? [duplicate]
- How to display source code with indent in a web page? HTML? CSS?
Displaying the text in a WebView is a great idea as you can now use javascript APIs like Google's Code Prettify
I believe SO uses it ;)
The comments in prettify.js are authoritative but the lexer should
work on a number of languages including C and friends, Java, Python,
Bash, SQL, HTML, XML, CSS, Javascript, Makefiles, and Rust.
It works passably on Ruby, PHP, VB, and Awk and a decent subset of
Perl and Ruby, but, because of commenting conventions, doesn't work on
Smalltalk, OCaml, etc. without a language extension.
Other languages are supported via extensions:
Apollo; Basic; Clojure; CSS; Dart; Erlang; Go; Haskell; Lasso; Lisp,
Scheme; Llvm; Logtalk; Lua; Matlab; MLs: F#, Ocaml,SML; Mumps;
Nemerle; Pascal; Protocol buffers; R, S; RD; Rust; Scala; SQL; Swift;
TCL; Latek; Visual Basic; VHDL; Wiki; XQ; YAML
I think this question is a tricky one. I tried to google myself and only find this library
https://android-arsenal.com/details/1/2049
which supports different text appearence. Hope this will help you out.

Html.fromHtml(String).toString(); gives css in starting String

protected String getEntryContent(String entryContent) {
Log.d(getClass().getName(), "getEntryContent()");
String mWebViewContent;
mWebView.loadDataWithBaseURL(baseUrl,
entryContent, mimeType,
encoding, null);
mWebViewContent =Html.fromHtml(entryContent).toString();
return mWebViewContent;
}
Output:
h2 {font-size:1.2em;font-weight:normal;} a {color:#6688cc;} ol {padding- left:1.5em;} blockquote {margin-left:0em;} .interProject, .noprint {display:none;} li, blockquote {margin-top:0.5em;margin-bottom:0.5em;}
quarterly (not comparable) Occurring once every quarter year (three months).
quarterly rent payments
This gives me starting line as a CSS.
How can i remove that?
You probably passed the inline CSS in your string. From the javadoc of HTML.fromHtml it nowhere states that it can handle inline css, therefore it propably handles it like normal text
Returns displayable styled text from the provided HTML string. Any tags in the HTML will use the specified ImageGetter to request a representation of the image (use null if you don't want this) and the specified TagHandler to handle unknown tags (specify null if you don't want this).
You have to remove the css manually yourself. See this answer on how to do that: Removing css information from HTML in java
You can use this:
CharSequence mSequence = Html.fromHtml("<b>Hello</b> Android");
textView.setText(mSequence);
You can also convert it into String as:
String mString = mSequence.toString();

How to format text in string displayed in TextView

I'm trying to format text in string, which is displyed in TextView.
<string name="register"> <p align="center"><u><b><i>Something</i></b></u></p>
<p align="right">Blablabla</p>
Underline, bolt and italics are working, but new paragraph and align isn't. Am I doing something wrong? Is there some other tag for end of a paragraph/new line?
Refer here http://bigknol.com/android-supported-html-tags-textview-string/
Not all html tags are supported in android. As per the link only the following tags are supported:
<big></big>
<small></small>
<bold></bold>
<strike></strike>
<a href=””></a>
<sup></sup>
<sub></sub>
<u></u>
<i></i>
<tt></tt>
Also refer here Which HTML tags are supported by Android TextView?
Another reference is here http://javatechig.com/android/display-html-in-android-textview
You can use
myTextView.setText(Html.fromHtml("<h2>Heading</h2><br><p>data about something</p>"));

Android - Class Html - fromHtml - How does it work?

I'm using Html.fromHtml to get the contents of a description tag (in a feed XML) and it works fine
Description tag:
<description><![CDATA[<div class="K2FeedIntroText"><p><img style="margin: 10px; float: left;" alt="block curta" src="http://loc.grupolusofona.pt/images/stories/destaques/block%20curta.jpg" height="110" width="120" />Quatro Horas Descalço é o nome da curta-metragem, realizada por Ico Costa, que se estreia mundialmente no 7.º Festival Internacional de Cinema de Roma, nos dias 12 e 13 de novembro, em competição no Cinema XXI.</p>
]]>
But as I go look into the documentation it says:
Returns displayable styled text from the provided HTML string. Any <img> tags in the HTML will display as a generic replacement image which your program can then go through and replace with real images.
So my question is: how can i do what it says there "which your program can then go through and replace with the real image" ?
I know how to get the img url via RegEx using a Pattern, i just wanted to know how can i use the class to "go through and replace it with the image"
Please say something if i was unclear and ill try to explain it better.
EDIT:
Well, i'm trying to implement this in a simple rss reader (and trying to keep it as simple as possible code-wise)
I'm using a DOM Parser and i'm using a map = HashMap<String, Spanned> to store the values of each child node, along with a KEY:
map.put(KEY_DESC, Html.fromHtml(parser.getValue(e, KEY_DESC)));
In the comments of the answer i found a useful link from which i created a new Class (URLImageParser) and tried to use it like so:
map.put(KEY_DESC, htmlSpan);
Where htmlSpan would be the result of:
this.textView = (TextView)this.findViewById(R.id.textview);
URLImageParser p = new URLImageParser(textView, this);
Spanned htmlSpan = Html.fromHtml(html, p, null);
textView.setText(htmlSpan);
I also created a android:visibility="gone" TextView just in case it needed to store the values in a TextView (maybe i interpreted it wrong)
My original thought was that htmlSpan was of the type Spanned so it would fit in my HashMap just fine.
For uploading to ListView i'm using a SimpleAdapter like so:
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.linhafeed,
new String[] { KEY_TITLE, KEY_DESC, KEY_PUBDATE, KEY_LINK },
new int[] { R.id.title, R.id.desc, R.id.pub, R.id.link });
Where menuItems is ArrayList<HashMap<String,Spanned>>
Something i got wrong here ?
Html.fromHtml(...) will replace any <img ... /> tag with an ImageSpan and a special 'object replacement character' (\uFFFC).
To get the actual image to show up, it looks like there are two options:
implement an ImageGetter that returns the image to display as a Drawable. If I recall correctly, this won't allow you to offload the image loading to a different thread, because it expects the result to be returned right away. Hence, this should suffice for local resources (and probably also any assets in a device's local storage, provided there are no potentially long-running operations required; i.e. scaling, cropping, applying effects etc).
do a second pass over the Spanned result and replace any \uFFFC occurrences. You should be able to get the source (url) of the image from every ImageSpan using the getSource() method. Unfortunately, it doesn't look there are any setters to update the Drawable once loaded, so I'm guessing you may need to replace the ImageSpan with a new one, passing in the loaded image in the constructor.
A third alternative, which may be a bit more heavy-weight than above, is to use a WebView rather than a TextView. That way you don't have to deal with any of the image loading yourself, as it's built into the widget.

Categories

Resources