How to extract text smileys from a string in android - android

I am working on an android application in which I want to convert all keyboard types smileys into emoji icons.
I am already using this library https://github.com/ankushsachdeva/emojicon to show Emoticons in my app.
Now, I want to convert the smileys which users will type using keyboard into emoticons.
Ex: If user type the string Hello World :) :P:
1. Then I need to first extract these smiley symbols and for that I need a regex pattern which will extract all these types of symbols from a string.
2. I need to find Unicode of these symbols and then convert these symbols in emoticons using the above library.
Please help me, so that I can proceed here.

this lib is using ImageSpans and SpannableStringBuilder like here:
EmojiconTextView
public void setText(CharSequence text, BufferType type) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mTextStart, mTextLength);
super.setText(builder, type);
}
you can always remove spans from current SpannableStringBuilder and get plain text
if you want to set spans "in fly" just use TextWatcher for your EditText, smth like here: EmojiconEditText
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
EmojiconHandler.addEmojis(getContext(), getText(), mEmojiconSize);
}
this lib seems to do all work for you, just use Views from lib (Emojicon prefix) instead usual ones, e.g.
<ankushsachdeva.emojicon.EmojiconTextView
android:id="#+id/emojicon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
emojicon:emojiconSize="24dip"
android:gravity="center"/>
instead EditText in XML layout files

Related

EditText with only ascii letters. How?

Primary users of my app have 2 languages installed. English and other. Default system language is not English.
Users just use language switch button on software keyboard.
One specific EditText field in my app needs to accept only A-Z(capitalization issue is not a problem) and spaces and no other characters (no digits, no non-latin chars,etc).
I understood about solutions with InputFilters like How to create EditText accepts Alphabets only in android? or with TextWatcher-derived but thy only allow app to simple ignore incorrect text and I need to be able to make user not even able to see non-latin1 letters in first place on their on-screen keyboard (I'm aware that it is possible to use hardware keyboard, this is not issue at this time).
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
Doesn't help too (language change button is still visible in keyboard).
I need something like iPhone: Change Keyboard language programmatically but for Android.
Do I have any other option except adding fake keyboard to my app?
iOS have .keyboardType = .asciiCapable and it works in such situations
You can use input filter and assign it to Edit texts
Refer to example below
public class AlphabetInputFilter implements InputFilter {
Pattern mPattern;
public AlphabetInputFilter() {
mPattern = Pattern.compile("[a-z]");
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String formatedSource = dest.subSequence(0, dstart).toString();
String destPrefix = source.subSequence(start, end).toString();
String destSuffix = dest.subSequence(dend, dest.length()).toString();
CharSequence match = TextUtils.concat(formatedSource, destPrefix, destSuffix);
Matcher matcher = mPattern.matcher(match);
if (!matcher.matches())
return "";
return null;
}
}
And you can assign it edit text
mEdittext.setFilters(new InputFilter[]{
new AlphabetInputFilter()});
user will not be able to enter any value other than a to z
I found at least semi-working solution based on https://stackoverflow.com/a/49710730/1063214
imeOptions="flagForceAscii"
on EditText.
Now at least non-english keyboard is not shown (and digits,etc are filtered anyway).

Adding a checkbox to a edittext/textview?

I have an application that needs a rich text editor.
I intend to implement this using spannables or assigning an html code as the text of the textview.
Can I add a checkbox in the same way?
To show html in TextView you should first convert in to Spanned using Html.fromHtml(). But only a small HTML tag subset can be used in this method because spannables are used for styling text. If you want to add checkbox then you should do this outside of TextView.
As far as CheckBox extended from TextView you can use setText method with you Spannable.
For example:
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(poweredBy + " " + company);
int start = poweredBy.length();
int end = spannableStringBuilder.length();
spannableStringBuilder.setSpan(new ForegroundColorSpan(companyColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
checkbox.setText(spannableStringBuilder);

How to process textview for HTML and Linkify

I am trying to get a textview to process a hyperlink as well as phone numbers. Say my text is:
"555-555-555, www.google.com, Google!"
If I run Html.fromHtml() on this string, then the TextView shows Google! correctly as a clickable link but not the other two.
If I run Linkify.addLinks(TextView, Linkify.All) on the TextView, then the first two are correctly recognized as a phone number and url, but the html is not processed in the last one.
If I run both of them, then either one or the other is honored, but not both at the same time. (Html.fromHtml will remove the html tags there, but it won't be a link if linkify is called after)
Any ideas on how to get both of these functions to work simultaneously? So all the links are processed correctly? Thanks!
Edit: Also, the text is changed dynamically so I'm not sure how I would be able to go about setting up a Linkify pattern for that.
It's because Html.fromHtml and Linkify.addLinks removes previous spans before processing the text.
Use this code to get it work:
public static Spannable linkifyHtml(String html, int linkifyMask) {
Spanned text = Html.fromHtml(html);
URLSpan[] currentSpans = text.getSpans(0, text.length(), URLSpan.class);
SpannableString buffer = new SpannableString(text);
Linkify.addLinks(buffer, linkifyMask);
for (URLSpan span : currentSpans) {
int end = text.getSpanEnd(span);
int start = text.getSpanStart(span);
buffer.setSpan(span, start, end, 0);
}
return buffer;
}
try to set movement method on your textview instead of using Linkify:
textView.setMovementMethod(LinkMovementMethod.getInstance());
In your TextView's xml layout, you should add the following:
android:autoLink="all"
android:linksClickable="true"
Then you should remove your Linkify code in Java.
It works somehow, but I dont know why. I added a question to see if someone can explain the behavior: Using Linkify.addLinks combine with Html.fromHtml

Android: Deleting characters in EditText with TextWatcher still shows characters in suggestions

In my activity I have an EditText to capture a file name. I am using a TextWatcher to prevent users from entering certain characters that I don't want them to use in their filename. Essentially I only want users to enter in the following characters: [a-zA-Z_0-9].
#Override
public void afterTextChanged(Editable text) {
String textStr = text.toString();
int length = text.length();
if (!Pattern.matches("\\w*", textStr)) {
text.delete(length-1, length);
}
}
EDIT: Adding more code
in onCreate(...)
fileNameEditText = (EditText)findViewById(R.id.UploadPhoto_fileNameEditText);
fileNameEditText.addTextChangedListener(this);
in layout xml file
<EditText
android:id="#+id/UploadPhoto.fileNameEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20sp"
android:layout_marginRight="10sp"
android:layout_toRightOf="#id/UploadPhoto.fileNameLabel"/>
This works perfectly by preventing users from entering in things like "\" and ".". The problem that I'm having is that if they type these characters they show up in the word suggestions box. Its kind of annoying because if you try to delete a character using backspace, it deletes from the suggestion first (even though the character doesn't show up in EditText box).
How do you prevent the unwanted characters from showing up in the word suggestiong box?
See screen shot below. Notice that the "-" (hyphen) appears in the suggestion box, but not in the EditText. Also notice that there is another valid character in the suggestion box after the hyphen that also does not show up in the EditText. This essentially blocks the user from entering in more text until they delete the hyphen, even though its not in the EditText.
UPDATE: The same issue arises and can be reproduced by using an InputFilter instead of a TextWatcher.
UPDATE: I'd like to clarify that my goal is not to suppress the Suggestions altogether. The issue is that when you prevent specific characters from appearing in the EditText, they still show up in the Suggestions. My goal (which the bounty is for) is to prevent the same specific characters from appearing in the Suggestions.
You should use an InputFilter to restrict some characters in Edittext
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isLetterOrDigit(source.charAt(i))) {
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
It seems that the emulator doesn't support the textNoSuggestions, and the corresponding FLAG (TYPE_TEXT_FLAG_NO_SUGGESTIONS). It's realy anoying, but hey: you're not developing for emulator users, you shouldn't be preoccupied with this, it'll work fine on allmost all devices.
(Note that this flag is available only from API level 5)
We can do that in the layout xml file and achive what you have asked in an easy way, insert the line
android:numeric="your custom elements"
android:digits="your custom elments"
android:inputType="your custom elements"
when you implement these then you will be able to type the words that you want to.

Specifying "strikethrough" on a section of TextView text

I have a block of text coming from a webservice, and depending on some tags which I have predefined, I want to style the text before setting it to my TextView. For bold, italics, and underline, I was able to do this easily with the replaceAll command:
PageText = PageText.replaceAll("\\*([a-zA-Z0-9]+)\\*", "<b>$1</b>");
PageText = PageText.replaceAll("=([a-zA-Z0-9]+)=", "<i>$1</i>");
PageText = PageText.replaceAll("_([a-zA-Z0-9]+)_", "<u>$1</u>");
txtPage.setText(Html.fromHtml(PageText), TextView.BufferType.SPANNABLE);
So, to bold a word, surround it with *'s, for italics, surround with _.
But, for strikethrough, Html.fromHtml does not support the "strike" tag, so it can't be done this same way. I've seen examples of using Spannable to set the styling on one section of text, but it requires positional numbers. So, I guess I could loop through the text, searching for - (the tag to represent the strike), then searching for the next one, spanning the text in between, and repeating for all such strings. It will end up being 10 lines of looping code as opposed to 1 for the others, so I'm wondering if there is a more elegant solution out there.
If it is just TextView you can strike through using paint flags
TextView tv=(TextView) v.findViewById(android.R.id.text1);
tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
#Suresh solution works if you want to strikethrough the entire TextView but if you want to strikethrough only some portions of the text then use the code below.
tvMRP.setText(text, TextView.BufferType.SPANNABLE);
Spannable spannable = (Spannable) tvMRP.getText();
spannable.setSpan(new StrikethroughSpan(), 3, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Here text is the text which we want out TextView to display, 3 is the no. of characters (starting from 0) from where the strikethrough will start.
You can do it with a custom TagHandler such as the one on this SO question:
Spanned parsed = Html.fromHtml(PageText, null, new MyHtmlTagHandler());
And the TagHandler implements the methods:
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if(tag.equalsIgnoreCase("strike") || tag.equals("s")) {
processStrike(opening, output);
}
}
....
Are you sure Html.fromHtml doesn't support <strike>? It's listed in this Commonsware blog post
It looks like is not really supported, at least it does not work on Android 3.1.
#RMS2 if text is small you can split it into two or three separate text views and apply flag only to the one which you want, not perfect for long texts ;(
Most of the applications we work in are going to use text somewhere throughout the project and thankfully, KTX provides some extension functions when it comes to these parts. For text, we essentially have some functions available for the SpannableStringBuilder class.
For example, after instantiating a Builder instance we can use the build methods to append some bold text:
textView.text =buildSpannedString {
strikeThrough {
append(
value ?: ""
)
}
}

Categories

Resources