Ok so I asked this yesterday:
AutoLink #mentions in a twitter client
I got my #mentions linking correctly. But in order to get it to work I had to take android:autoLink="web" out my xml for the TextView. So now I get links to #mentions but it no longer links URLs. I tried doing two seperate Linkify.addLinks() calls like this:
mentionFilter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return match.group(1);
}
};
// Match #mentions and capture just the username portion of the text.
//pattern = Pattern.compile("#([A-Za-z0-9_-]+)");
pattern = Pattern.compile("(#[a-zA-Z0-9_]+)");
scheme = "http://twitter.com/";
tweetTxt = (TextView) v.findViewById(R.id.tweetTxt);
Linkify.addLinks(tweetTxt, pattern, scheme, null, mentionFilter);
Linkify.addLinks(tweetTxt, Linkify.WEB_URLS);
But which ever gets called last is the one that gets applied. Can anyone tell me how I can make it link both the #mentions and still autoLink the URLs?
Edited to clarify some more of the code.
Here's my code to linkify all Twitter links (mentions, hashtags and URLs):
TextView tweet = (TextView) findViewById(R.id.tweet);
TransformFilter filter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return match.group();
}
};
Pattern mentionPattern = Pattern.compile("#([A-Za-z0-9_-]+)");
String mentionScheme = "http://www.twitter.com/";
Linkify.addLinks(tweet, mentionPattern, mentionScheme, null, filter);
Pattern hashtagPattern = Pattern.compile("#([A-Za-z0-9_-]+)");
String hashtagScheme = "http://www.twitter.com/search/";
Linkify.addLinks(tweet, hashtagPattern, hashtagScheme, null, filter);
Pattern urlPattern = Patterns.WEB_URL;
Linkify.addLinks(tweet, urlPattern, null, null, filter);
I had to Linkify.ALL before Linkify-ing the # mentions for it to work.
Also, do not use 'android:autoLink' in the TextView in your XML layout file
TextView textView = (TextView) findViewById(R.id.tweet);
Pattern atMentionPattern = Pattern.compile("#([A-Za-z0-9_]+)");
String atMentionScheme = "http://twitter.com/";
TransformFilter transformFilter = new TransformFilter() {
//skip the first character to filter out '#'
public String transformUrl(final Matcher match, String url) {
return match.group(1);
}
};
Linkify.addLinks(textView, Linkify.ALL);
Linkify.addLinks(textView, atMentionPattern, atMentionScheme, null, transformFilter);
My TextView looks like this:
<TextView
android:id="#+id/tweet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColorLink="#449def"/>
Ok finally got some time to properly put in the #mention and #hashtags to a Linkify class. Instead of just overriding some of the other types of links to get it working.
This class works just like the normal Linkify, but also can do those two things.
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.use.your.own.package;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.text.style.URLSpan;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.webkit.WebView;
import android.widget.TextView;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Linkify take a piece of text and a regular expression and turns all of the
* regex matches in the text into clickable links. This is particularly
* useful for matching things like email addresses, web urls, etc. and making
* them actionable.
*
* Alone with the pattern that is to be matched, a url scheme prefix is also
* required. Any pattern match that does not begin with the supplied scheme
* will have the scheme prepended to the matched text when the clickable url
* is created. For instance, if you are matching web urls you would supply
* the scheme <code>http://</code>. If the pattern matches example.com, which
* does not have a url scheme prefix, the supplied scheme will be prepended to
* create <code>http://example.com</code> when the clickable url link is
* created.
*/
public class LinkifyWithTwitter {
/**
* Bit field indicating that web URLs should be matched in methods that
* take an options mask
*/
public static final int WEB_URLS = 0x01;
/**
* Bit field indicating that email addresses should be matched in methods
* that take an options mask
*/
public static final int EMAIL_ADDRESSES = 0x02;
/**
* Bit field indicating that phone numbers should be matched in methods that
* take an options mask
*/
public static final int PHONE_NUMBERS = 0x04;
/**
* Bit field indicating that twitter #mentions should be matched in methods that
* take an options mask
*/
public static final int AT_MENTIONS = 0x05;
/**
* Bit field indicating that #hash-tags should be matched in methods that
* take an options mask
*/
public static final int HASH_TAGS = 0x06;
/**
* Bit field indicating that street addresses should be matched in methods that
* take an options mask
*/
public static final int MAP_ADDRESSES = 0x08;
/**
* Bit mask indicating that all available patterns should be matched in
* methods that take an options mask
*/
public static final int ALL = WEB_URLS | EMAIL_ADDRESSES | PHONE_NUMBERS | AT_MENTIONS| HASH_TAGS |MAP_ADDRESSES;
/**
* Don't treat anything with fewer than this many digits as a
* phone number.
*/
private static final int PHONE_NUMBER_MINIMUM_DIGITS = 5;
/**
* Filters out web URL matches that occur after an at-sign (#). This is
* to prevent turning the domain name in an email address into a web link.
*/
public static final MatchFilter sUrlMatchFilter = new MatchFilter() {
public final boolean acceptMatch(CharSequence s, int start, int end) {
if (start == 0) {
return true;
}
if (s.charAt(start - 1) == '#') {
return false;
}
return true;
}
};
/**
* Filters out URL matches that don't have enough digits to be a
* phone number.
*/
public static final MatchFilter sPhoneNumberMatchFilter = new MatchFilter() {
public final boolean acceptMatch(CharSequence s, int start, int end) {
int digitCount = 0;
for (int i = start; i < end; i++) {
if (Character.isDigit(s.charAt(i))) {
digitCount++;
if (digitCount >= PHONE_NUMBER_MINIMUM_DIGITS) {
return true;
}
}
}
return false;
}
};
/**
* Transforms matched phone number text into something suitable
* to be used in a tel: URL. It does this by removing everything
* but the digits and plus signs. For instance:
* '+1 (919) 555-1212'
* becomes '+19195551212'
*/
public static final TransformFilter sPhoneNumberTransformFilter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return Regex.digitsAndPlusOnly(match);
}
};
/**
* MatchFilter enables client code to have more control over
* what is allowed to match and become a link, and what is not.
*
* For example: when matching web urls you would like things like
* http://www.example.com to match, as well as just example.com itelf.
* However, you would not want to match against the domain in
* support#example.com. So, when matching against a web url pattern you
* might also include a MatchFilter that disallows the match if it is
* immediately preceded by an at-sign (#).
*/
public interface MatchFilter {
/**
* Examines the character span matched by the pattern and determines
* if the match should be turned into an actionable link.
*
* #param s The body of text against which the pattern
* was matched
* #param start The index of the first character in s that was
* matched by the pattern - inclusive
* #param end The index of the last character in s that was
* matched - exclusive
*
* #return Whether this match should be turned into a link
*/
boolean acceptMatch(CharSequence s, int start, int end);
}
/**
* TransformFilter enables client code to have more control over
* how matched patterns are represented as URLs.
*
* For example: when converting a phone number such as (919) 555-1212
* into a tel: URL the parentheses, white space, and hyphen need to be
* removed to produce tel:9195551212.
*/
public interface TransformFilter {
/**
* Examines the matched text and either passes it through or uses the
* data in the Matcher state to produce a replacement.
*
* #param match The regex matcher state that found this URL text
* #param url The text that was matched
*
* #return The transformed form of the URL
*/
String transformUrl(final Matcher match, String url);
}
/**
* Scans the text of the provided Spannable and turns all occurrences
* of the link types indicated in the mask into clickable links.
* If the mask is nonzero, it also removes any existing URLSpans
* attached to the Spannable, to avoid problems if you call it
* repeatedly on the same text.
*/
public static final boolean addLinks(Spannable text, int mask) {
if (mask == 0) {
return false;
}
URLSpan[] old = text.getSpans(0, text.length(), URLSpan.class);
for (int i = old.length - 1; i >= 0; i--) {
text.removeSpan(old[i]);
}
ArrayList<LinkSpec> links = new ArrayList<LinkSpec>();
if ((mask & WEB_URLS) != 0) {
gatherLinks(links, text, Regex.WEB_URL_PATTERN,
new String[] { "http://", "https://" },
sUrlMatchFilter, null);
}
if ((mask & EMAIL_ADDRESSES) != 0) {
gatherLinks(links, text, Regex.EMAIL_ADDRESS_PATTERN,
new String[] { "mailto:" },
null, null);
}
if ((mask & PHONE_NUMBERS) != 0) {
gatherLinks(links, text, Regex.PHONE_PATTERN,
new String[] { "tel:" },
sPhoneNumberMatchFilter, sPhoneNumberTransformFilter);
}
if((mask & AT_MENTIONS) != 0){
gatherLinks(links, text, Pattern.compile("#([A-Za-z0-9_-]+)"),
new String[] { "http://www.twitter.com/" },
null, null);
}
if((mask & HASH_TAGS) != 0){
TransformFilter hashTagFilter = new TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return match.group(0).replaceAll("#", "%23");
}
};
gatherLinks(links, text, Pattern.compile("#([A-Za-z0-9_-]+)"),
new String[] { "http://twitter.com/#!/search/" },
null,hashTagFilter);
}
if ((mask & MAP_ADDRESSES) != 0) {
gatherMapLinks(links, text);
}
pruneOverlaps(links);
if (links.size() == 0) {
return false;
}
for (LinkSpec link: links) {
applyLink(link.url, link.start, link.end, text);
}
return true;
}
/**
* Scans the text of the provided TextView and turns all occurrences of
* the link types indicated in the mask into clickable links. If matches
* are found the movement method for the TextView is set to
* LinkMovementMethod.
*/
public static final boolean addLinks(TextView text, int mask) {
if (mask == 0) {
return false;
}
CharSequence t = text.getText();
if (t instanceof Spannable) {
if (addLinks((Spannable) t, mask)) {
addLinkMovementMethod(text);
return true;
}
return false;
} else {
SpannableString s = SpannableString.valueOf(t);
if (addLinks(s, mask)) {
addLinkMovementMethod(text);
text.setText(s);
return true;
}
return false;
}
}
private static final void addLinkMovementMethod(TextView t) {
MovementMethod m = t.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (t.getLinksClickable()) {
t.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
/**
* Applies a regex to the text of a TextView turning the matches into
* links. If links are found then UrlSpans are applied to the link
* text match areas, and the movement method for the text is changed
* to LinkMovementMethod.
*
* #param text TextView whose text is to be marked-up with links
* #param pattern Regex pattern to be used for finding links
* #param scheme Url scheme string (eg <code>http://</code> to be
* prepended to the url of links that do not have
* a scheme specified in the link text
*/
public static final void addLinks(TextView text, Pattern pattern, String scheme) {
addLinks(text, pattern, scheme, null, null);
}
/**
* Applies a regex to the text of a TextView turning the matches into
* links. If links are found then UrlSpans are applied to the link
* text match areas, and the movement method for the text is changed
* to LinkMovementMethod.
*
* #param text TextView whose text is to be marked-up with links
* #param p Regex pattern to be used for finding links
* #param scheme Url scheme string (eg <code>http://</code> to be
* prepended to the url of links that do not have
* a scheme specified in the link text
* #param matchFilter The filter that is used to allow the client code
* additional control over which pattern matches are
* to be converted into links.
*/
public static final void addLinks(TextView text, Pattern p, String scheme,
MatchFilter matchFilter, TransformFilter transformFilter) {
SpannableString s = SpannableString.valueOf(text.getText());
if (addLinks(s, p, scheme, matchFilter, transformFilter)) {
text.setText(s);
addLinkMovementMethod(text);
}
}
/**
* Applies a regex to a Spannable turning the matches into
* links.
*
* #param text Spannable whose text is to be marked-up with
* links
* #param pattern Regex pattern to be used for finding links
* #param scheme Url scheme string (eg <code>http://</code> to be
* prepended to the url of links that do not have
* a scheme specified in the link text
*/
public static final boolean addLinks(Spannable text, Pattern pattern, String scheme) {
return addLinks(text, pattern, scheme, null, null);
}
/**
* Applies a regex to a Spannable turning the matches into
* links.
*
* #param s Spannable whose text is to be marked-up with
* links
* #param p Regex pattern to be used for finding links
* #param scheme Url scheme string (eg <code>http://</code> to be
* prepended to the url of links that do not have
* a scheme specified in the link text
* #param matchFilter The filter that is used to allow the client code
* additional control over which pattern matches are
* to be converted into links.
*/
public static final boolean addLinks(Spannable s, Pattern p,
String scheme, MatchFilter matchFilter,
TransformFilter transformFilter) {
boolean hasMatches = false;
String prefix = (scheme == null) ? "" : scheme.toLowerCase();
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
boolean allowed = true;
if (matchFilter != null) {
allowed = matchFilter.acceptMatch(s, start, end);
}
if (allowed) {
String url = makeUrl(m.group(0), new String[] { prefix },
m, transformFilter);
applyLink(url, start, end, s);
hasMatches = true;
}
}
return hasMatches;
}
private static final void applyLink(String url, int start, int end, Spannable text) {
URLSpan span = new URLSpan(url);
text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private static final String makeUrl(String url, String[] prefixes,
Matcher m, TransformFilter filter) {
if (filter != null) {
url = filter.transformUrl(m, url);
}
boolean hasPrefix = false;
for (int i = 0; i < prefixes.length; i++) {
if (url.regionMatches(true, 0, prefixes[i], 0,
prefixes[i].length())) {
hasPrefix = true;
// Fix capitalization if necessary
if (!url.regionMatches(false, 0, prefixes[i], 0,
prefixes[i].length())) {
url = prefixes[i] + url.substring(prefixes[i].length());
}
break;
}
}
if (!hasPrefix) {
url = prefixes[0] + url;
}
return url;
}
private static final void gatherLinks(ArrayList<LinkSpec> links,
Spannable s, Pattern pattern, String[] schemes,
MatchFilter matchFilter, TransformFilter transformFilter) {
Matcher m = pattern.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
if (matchFilter == null || matchFilter.acceptMatch(s, start, end)) {
LinkSpec spec = new LinkSpec();
String url = makeUrl(m.group(0), schemes, m, transformFilter);
spec.url = url;
spec.start = start;
spec.end = end;
links.add(spec);
}
}
}
private static final void gatherMapLinks(ArrayList<LinkSpec> links, Spannable s) {
String string = s.toString();
String address;
int base = 0;
while ((address = WebView.findAddress(string)) != null) {
int start = string.indexOf(address);
if (start < 0) {
break;
}
LinkSpec spec = new LinkSpec();
int length = address.length();
int end = start + length;
spec.start = base + start;
spec.end = base + end;
string = string.substring(end);
base += end;
String encodedAddress = null;
try {
encodedAddress = URLEncoder.encode(address,"UTF-8");
} catch (UnsupportedEncodingException e) {
continue;
}
spec.url = "geo:0,0?q=" + encodedAddress;
links.add(spec);
}
}
private static final void pruneOverlaps(ArrayList<LinkSpec> links) {
Comparator<LinkSpec> c = new Comparator<LinkSpec>() {
public final int compare(LinkSpec a, LinkSpec b) {
if (a.start < b.start) {
return -1;
}
if (a.start > b.start) {
return 1;
}
if (a.end < b.end) {
return 1;
}
if (a.end > b.end) {
return -1;
}
return 0;
}
public final boolean equals(Object o) {
return false;
}
};
Collections.sort(links, c);
int len = links.size();
int i = 0;
while (i < len - 1) {
LinkSpec a = links.get(i);
LinkSpec b = links.get(i + 1);
int remove = -1;
if ((a.start <= b.start) && (a.end > b.start)) {
if (b.end <= a.end) {
remove = i + 1;
} else if ((a.end - a.start) > (b.end - b.start)) {
remove = i + 1;
} else if ((a.end - a.start) < (b.end - b.start)) {
remove = i;
}
if (remove != -1) {
links.remove(remove);
len--;
continue;
}
}
i++;
}
}
}
class LinkSpec {
String url;
int start;
int end;
}
I figured out a way to make this work. It is a little bit hacky but it got the job done. If anyone knows of a more appropriate way to do this please do let me know.
To get it working I made myself a copy of the Linkify class and edited the part that handles the linkifying for phone numbers to do #mention links instead.
Here is where I found my copy of the linkify class
I changed this:
if ((mask & PHONE_NUMBERS) != 0) {
gatherLinks(links, text, Regex.PHONE_PATTERN,
new String[] { "tel:" },
sPhoneNumberMatchFilter, sPhoneNumberTransformFilter);
}
into this:
if ((mask & PHONE_NUMBERS) != 0) {
gatherLinks(links, text, Pattern.compile("#([A-Za-z0-9_-]+)"),
new String[] { "http://www.twitter.com/" },
null, null);
}
I called this class MyLinkify and used this code in my Activity to apply the links.
MyLinkify.addLinks(tweetTxt, Linkify.ALL);
To get the MyLinkify class to build I also had to add a copy of the Regex class into my project, here is where I found Regex.java
Im putting this as an answer incase anyone else looking for this effect finds this thread. I realized this is probably not the best way to go about getting this to work. If anyone knows a better way to get it working please add it here and I'll select it is the actual answer to this question.
use below code:
TextView textView = (TextView) findViewById(R.id.hello);
String str = "#aman_vivek how are u #aman_vivek <http://www.google.com> <http://www.tekritisoftware.com>";
textView.setText(str);
Pattern wikiWordMatcher = Pattern.compile("(#[a-zA-Z0-9_]+)");
String wikiViewURL = "http://www.twitter.com/";
Linkify.addLinks(textView, wikiWordMatcher, wikiViewURL);
Pattern wikiWordMatcher1 = Pattern.compile("\\b(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]");
Linkify.addLinks(textView, wikiWordMatcher1, null);
Is tweetTxt the input String that you are linkifying or a handle to the TextView object?
If its the input string, then you are just overwriting the TextView with the output of the final call to addLinks. Given your observation, I'm guessing this is the case.
You need to pass the TextView to addLinks in both cases. Internally, Linkify will pluck the Spanned buffer from the TextView and use that, such that multiple calls to addLinks are cumulative. The WikiNotes example passes the TextView and so should you: http://developer.android.com/resources/articles/wikinotes-linkify.html
Related
It may be dumb question am using horizontal mpandroid barchart am having numbers in x axis like 6,000,000 so x axis getting collapsed so what is need to do is convert the number into indian rupees like 6 cr how can i do this so far what i have tried is:
This is where am setting value for horizontal barchart:
ArrayList<BarEntry> entries = new ArrayList<>();
ArrayList<String> labels = new ArrayList<String>();
Format format = NumberFormat.getCurrencyInstance(new Locale("en", "in"));
// System.out.println(format.format(new BigDecimal("100000000")));
for(int i=0;i<listobj.size();i++){
String s= format.format(listobj.get(i).getData());
// Log.e("ss", s);
// Integer numberformat=Integer.parseInt(s);
entries.add(new BarEntry(listobj.get(i).getData(),i));
labels.add(listobj.get(i).getLabel());
}
XAxis axis=barChart.getXAxis();
BarDataSet dataset = new BarDataSet(entries, "# of Calls");
//dataset.setValueFormatter(new LargeValueFormatter());
BarData datas = new BarData(labels, dataset);
/// datas.setValueFormatter(new LargeValueFormatter());
barChart.setData(datas);
barChart.setDescription("Description");
barChart.getLegend().setWordWrapEnabled(true);
This is value Formatter:
/**
* Created by 4264 on 30-05-2016.
*/
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.text.DecimalFormat;
/**
* Predefined value-formatter that formats large numbers in a pretty way.
* Outputs: 856 = 856; 1000 = 1k; 5821 = 5.8k; 10500 = 10k; 101800 = 102k;
* 2000000 = 2m; 7800000 = 7.8m; 92150000 = 92m; 123200000 = 123m; 9999999 =
* 10m; 1000000000 = 1b; Special thanks to Roman Gromov
* (https://github.com/romangromov) for this piece of code.
*
* #author Philipp Jahoda
* #author Oleksandr Tyshkovets <olexandr.tyshkovets#gmail.com>
*/
class LargeValueFormatter implements ValueFormatter {
private static String[] SUFFIX = new String[]{
"", "k", "m", "b", "t"
};
private static final int MAX_LENGTH = 4;
private DecimalFormat mFormat;
private String mText = "";
public LargeValueFormatter() {
mFormat = new DecimalFormat("###E0");
}
/**
* Creates a formatter that appends a specified text to the result string
*
* #param appendix a text that will be appended
*/
public LargeValueFormatter(String appendix) {
this();
mText = appendix;
}
// ValueFormatter
#Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return makePretty(value) + mText;
}
// YAxisValueFormatter
/**
* Set an appendix text to be added at the end of the formatted value.
*
* #param appendix
*/
public void setAppendix(String appendix) {
this.mText = appendix;
}
/**
* Set custom suffix to be appended after the values.
* Default suffix: ["", "k", "m", "b", "t"]
*
* #param suff new suffix
*/
public void setSuffix(String[] suff) {
if (suff.length == 5) {
SUFFIX = suff;
}
}
/**
* Formats each number properly. Special thanks to Roman Gromov
* (https://github.com/romangromov) for this piece of code.
*/
private String makePretty(double number) {
String r = mFormat.format(number);
r = r.replaceAll("E[0-9]", SUFFIX[Character.getNumericValue(r.charAt(r.length() - 1)) / 3]);
while (r.length() > MAX_LENGTH || r.matches("[0-9]+\\.[a-z]")) {
r = r.substring(0, r.length() - 2) + r.substring(r.length() - 1);
}
return r;
}
}
I don't know how to customize the x axis value how can i do this can anyone help me out thanks in advance!!
You have 2 options that you can try to solve your issue
1) While inserting the value you can divide the value by 1000,000 and change your label to 6Cr . I have a chart that has values from 0 to 30 and one value is 4000. While storing the value in database I divide it by 100 and while displaying I change the label to show the correct value
Sample SQL insert value :
Float.valueOf(LEUCO_COUNT.getText().toString()) / 1000,
2) Option 2 is to divide the value by 1000,000 before displaying it and also modify your babel to show Cr. You can go throught he API to find how to set a custom label
Hope this helps.
You need to replace existing function with below function.It working for me.
private String makePretty(double number) {
double Cr = 10000000;
double Lac = 100000;
String result = mFormat.format(number);
try {
double LAmt = Double.parseDouble(result);
String Append = "";
if (LAmt > Cr) {//1Crore
LAmt /= Cr;
Append = "Cr";
} else {
LAmt /= Lac;
Append = "L";
}
result = CommonUtils.GetFormattedString("" + LAmt) + Append;
} catch (NumberFormatException e) {
Log.d("", "");
}
return result;
}
I have 2 edittexts and 1 textview. 1 edittext for input the price another one the percentage and the textview will display the result of them both (the price * percentage/100) and i want to make the 1st edittext input(for the price) will change the format of the input and display it on the same edittext with decimal format. For example :
edittext1
100
the user type 100 it will just display 100 ,but when the user type one or more number(S) it will add "," every 3 number
edittext1
1,000
edittext1
10,000
edittext1
100,000
edittext1
1,000,000
and so on
i have the functions, one will autocalculate the value for textview1 , another will convert automatically the input of edittext. However they cant work together because the format for calculation function, it uses int/long/double and for the converter it uses decimalformat . If i use them both the app will crash with javanumberformatexception unable to parse int "1,000"(if we put 1000 into edittext)
my function for autocalculate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simulasikredit);
ethint1 = (EditText) findViewById(R.id.ethint);
etpersen2 = (EditText) findViewById(R.id.etpersen);
textvDP1 = (TextView) findViewById(R.id.textvDP);
etpersen2.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text1 = ethint1.getText().toString();
String text2 = etpersen2.getText().toString();
long input1 = 0;
long input2 = 0;
if(text1.length()>0)
input1 = Long.valueOf(text1);
if(text2.length()>0)
input2 = Long.valueOf(text2);
if (text1.length() != 0) {
long output = (input1 * input2) / 100;
textvDP1.setText(""+output);
}
else if(text2.length() == 0){
textvDP1.setText("");
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
}); }
et stands for edittext, tv stands for textview
and makedecimal function
public void makedecimal(View v)
{
ethint1.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
DigitsKeyListener dkl = new DigitsKeyListener(true,true);
ethint1.setKeyListener(dkl);
ethint1.addTextChangedListener(new TextWatcher(){
private String current = "";
#Override
public void afterTextChanged(Editable s) {
String userInput=s.toString();
if(!userInput.toString().equals(current)){
ethint1.removeTextChangedListener(this);
String cleanString = userInput.replaceAll("[,]", "");
if(cleanString.length()>0){
double parsed = Double.parseDouble(cleanString);
String formated = DecimalFormat.getNumberInstance().format(parsed);
current = formated;
ethint1.setText(formated);
ethint1.setSelection(formated.length());
}else{
ethint1.setText(cleanString);
ethint1.setSelection(cleanString.length());
}
ethint1.addTextChangedListener(this);
}
this makedecimal is android:onClick from ethint , ethint is the id(these two come from 1 edittext)
I need to fulfil a similar requirements before where we need to format the number in thousands and also support fractions.
My approach is to register a TextWatcher format text every time input changed, and provide a public method to get numeric value by stripping separators, which is quite tricky. My solution also caters for locale-specific separator by utilizing DecimalFormatSymbols class.
private final char GROUPING_SEPARATOR = DecimalFormatSymbols.getInstance().getGroupingSeparator();
private final char DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator();
...
/**
* Return numeric value repesented by the text field
* #return numeric value or {#link Double.NaN} if not a number
*/
public double getNumericValue() {
String original = getText().toString().replaceAll(mNumberFilterRegex, "");
if (hasCustomDecimalSeparator) {
// swap custom decimal separator with locale one to allow parsing
original = StringUtils.replace(original,
String.valueOf(mDecimalSeparator), String.valueOf(DECIMAL_SEPARATOR));
}
try {
return NumberFormat.getInstance().parse(original).doubleValue();
} catch (ParseException e) {
return Double.NaN;
}
}
/**
* Add grouping separators to string
* #param original original string, may already contains incorrect grouping separators
* #return string with correct grouping separators
*/
private String format(final String original) {
final String[] parts = original.split("\\" + mDecimalSeparator, -1);
String number = parts[0] // since we split with limit -1 there will always be at least 1 part
.replaceAll(mNumberFilterRegex, "")
.replaceFirst(LEADING_ZERO_FILTER_REGEX, "");
// only add grouping separators for non custom decimal separator
if (!hasCustomDecimalSeparator) {
// add grouping separators, need to reverse back and forth since Java regex does not support
// right to left matching
number = StringUtils.reverse(
StringUtils.reverse(number).replaceAll("(.{3})", "$1" + GROUPING_SEPARATOR));
// remove leading grouping separator if any
number = StringUtils.removeStart(number, String.valueOf(GROUPING_SEPARATOR));
}
// add fraction part if any
if (parts.length > 1) {
number += mDecimalSeparator + parts[1];
}
return number;
}
It's quite tedious to elaborate here so I'll only give a link for your own reading:
https://gist.github.com/hidroh/77ca470bbb8b5b556901
I have a TextView which is rendering basic HTML, containing 2+ links. I need to capture clicks on the links and open the links -- in my own internal WebView (not in the default browser.)
The most common method to handle link rendering seems to be like this:
String str_links = "<a href='http://google.com'>Google</a><br /><a href='http://facebook.com'>Facebook</a>";
text_view.setLinksClickable(true);
text_view.setMovementMethod(LinkMovementMethod.getInstance());
text_view.setText( Html.fromHtml( str_links ) );
However, this causes the links to open in the default internal web browser (showing the "Complete Action Using..." dialog).
I tried implementing a onClickListener, which properly gets triggered when the link is clicked, but I don't know how to determine WHICH link was clicked...
text_view.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// what now...?
}
});
Alternatively, I tried creating a custom LinkMovementMethod class and implementing onTouchEvent...
public boolean onTouchEvent(TextView widget, Spannable text, MotionEvent event) {
String url = text.toString();
// this doesn't work because the text is not necessarily a URL, or even a single link...
// eg, I don't know how to extract the clicked link from the greater paragraph of text
return false;
}
Ideas?
Example solution
I came up with a solution which parses the links out of a HTML string and makes them clickable, and then lets you respond to the URL.
Based upon another answer, here's a function setTextViewHTML() which parses the links out of a HTML string and makes them clickable, and then lets you respond to the URL.
protected void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span)
{
int start = strBuilder.getSpanStart(span);
int end = strBuilder.getSpanEnd(span);
int flags = strBuilder.getSpanFlags(span);
ClickableSpan clickable = new ClickableSpan() {
public void onClick(View view) {
// Do something with span.getURL() to handle the link click...
}
};
strBuilder.setSpan(clickable, start, end, flags);
strBuilder.removeSpan(span);
}
protected void setTextViewHTML(TextView text, String html)
{
CharSequence sequence = Html.fromHtml(html);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
for(URLSpan span : urls) {
makeLinkClickable(strBuilder, span);
}
text.setText(strBuilder);
text.setMovementMethod(LinkMovementMethod.getInstance());
}
I made an easy extension function in Kotlin to catch url link clicks in a TextView by applying a new callback to URLSpan elements.
strings.xml (example link in text)
<string name="link_string">this is my link: CLICK</string>
Make sure your spanned text is set to the TextView before you call "handleUrlClicks"
textView.text = getString(R.string.link_string)
This is the extension function:
/**
* Searches for all URLSpans in current text replaces them with our own ClickableSpans
* forwards clicks to provided function.
*/
fun TextView.handleUrlClicks(onClicked: ((String) -> Unit)? = null) {
//create span builder and replaces current text with it
text = SpannableStringBuilder.valueOf(text).apply {
//search for all URL spans and replace all spans with our own clickable spans
getSpans(0, length, URLSpan::class.java).forEach {
//add new clickable span at the same position
setSpan(
object : ClickableSpan() {
override fun onClick(widget: View) {
onClicked?.invoke(it.url)
}
},
getSpanStart(it),
getSpanEnd(it),
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
//remove old URLSpan
removeSpan(it)
}
}
//make sure movement method is set
movementMethod = LinkMovementMethod.getInstance()
}
This is how I call it:
textView.handleUrlClicks { url ->
Timber.d("click on found span: $url")
}
You've done as follows:
text_view.setMovementMethod(LinkMovementMethod.getInstance());
text_view.setText( Html.fromHtml( str_links ) );
have you tried in reverse order as shown below?
text_view.setText( Html.fromHtml( str_links ) );
text_view.setMovementMethod(LinkMovementMethod.getInstance());
and without:
text_view.setLinksClickable(true);
This can be simply solved by using Spannable String.What you really want to do (Business Requirement) is little bit unclear to me so following code will not give exact answer to your situation but i am petty sure that it will give you some idea and you will be able to solve your problem based on the following code.
As you do, i'm also getting some data via HTTP response and i have added some additional underlined text in my case "more" and this underlined text will open the web browser on click event.Hope this will help you.
TextView decription = (TextView)convertView.findViewById(R.id.library_rss_expan_chaild_des_textView);
String dec=d.get_description()+"<a href='"+d.get_link()+"'><u>more</u></a>";
CharSequence sequence = Html.fromHtml(dec);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
UnderlineSpan[] underlines = strBuilder.getSpans(0, 10, UnderlineSpan.class);
for(UnderlineSpan span : underlines) {
int start = strBuilder.getSpanStart(span);
int end = strBuilder.getSpanEnd(span);
int flags = strBuilder.getSpanFlags(span);
ClickableSpan myActivityLauncher = new ClickableSpan() {
public void onClick(View view) {
Log.e(TAG, "on click");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(d.get_link()));
mContext.startActivity(intent);
}
};
strBuilder.setSpan(myActivityLauncher, start, end, flags);
}
decription.setText(strBuilder);
decription.setLinksClickable(true);
decription.setMovementMethod(LinkMovementMethod.getInstance());
I've had the same problem but a lot of text mixed with few links and emails.
I think using 'autoLink' is a easier and cleaner way to do it:
text_view.setText( Html.fromHtml( str_links ) );
text_view.setLinksClickable(true);
text_view.setAutoLinkMask(Linkify.ALL); //to open links
You can set Linkify.EMAIL_ADDRESSES or Linkify.WEB_URLS if there's only one of them
you want to use or set from the XML layout
android:linksClickable="true"
android:autoLink="web|email"
The available options are:
none, web, email, phone, map, all
Solution
I have implemented a small class with the help of which you can handle long clicks on TextView itself and Taps on the links in the TextView.
Layout
TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="all"/>
TextViewClickMovement.java
import android.content.Context;
import android.text.Layout;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Patterns;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;
public class TextViewClickMovement extends LinkMovementMethod {
private final String TAG = TextViewClickMovement.class.getSimpleName();
private final OnTextViewClickMovementListener mListener;
private final GestureDetector mGestureDetector;
private TextView mWidget;
private Spannable mBuffer;
public enum LinkType {
/** Indicates that phone link was clicked */
PHONE,
/** Identifies that URL was clicked */
WEB_URL,
/** Identifies that Email Address was clicked */
EMAIL_ADDRESS,
/** Indicates that none of above mentioned were clicked */
NONE
}
/**
* Interface used to handle Long clicks on the {#link TextView} and taps
* on the phone, web, mail links inside of {#link TextView}.
*/
public interface OnTextViewClickMovementListener {
/**
* This method will be invoked when user press and hold
* finger on the {#link TextView}
*
* #param linkText Text which contains link on which user presses.
* #param linkType Type of the link can be one of {#link LinkType} enumeration
*/
void onLinkClicked(final String linkText, final LinkType linkType);
/**
*
* #param text Whole text of {#link TextView}
*/
void onLongClick(final String text);
}
public TextViewClickMovement(final OnTextViewClickMovementListener listener, final Context context) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new SimpleOnGestureListener());
}
#Override
public boolean onTouchEvent(final TextView widget, final Spannable buffer, final MotionEvent event) {
mWidget = widget;
mBuffer = buffer;
mGestureDetector.onTouchEvent(event);
return false;
}
/**
* Detects various gestures and events.
* Notify users when a particular motion event has occurred.
*/
class SimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onDown(MotionEvent event) {
// Notified when a tap occurs.
return true;
}
#Override
public void onLongPress(MotionEvent e) {
// Notified when a long press occurs.
final String text = mBuffer.toString();
if (mListener != null) {
Log.d(TAG, "----> Long Click Occurs on TextView with ID: " + mWidget.getId() + "\n" +
"Text: " + text + "\n<----");
mListener.onLongClick(text);
}
}
#Override
public boolean onSingleTapConfirmed(MotionEvent event) {
// Notified when tap occurs.
final String linkText = getLinkText(mWidget, mBuffer, event);
LinkType linkType = LinkType.NONE;
if (Patterns.PHONE.matcher(linkText).matches()) {
linkType = LinkType.PHONE;
}
else if (Patterns.WEB_URL.matcher(linkText).matches()) {
linkType = LinkType.WEB_URL;
}
else if (Patterns.EMAIL_ADDRESS.matcher(linkText).matches()) {
linkType = LinkType.EMAIL_ADDRESS;
}
if (mListener != null) {
Log.d(TAG, "----> Tap Occurs on TextView with ID: " + mWidget.getId() + "\n" +
"Link Text: " + linkText + "\n" +
"Link Type: " + linkType + "\n<----");
mListener.onLinkClicked(linkText, linkType);
}
return false;
}
private String getLinkText(final TextView widget, final Spannable buffer, final MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);
if (link.length != 0) {
return buffer.subSequence(buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0])).toString();
}
return "";
}
}
}
Usage
String str_links = "<a href='http://google.com'>Google</a><br /><a href='http://facebook.com'>Facebook</a>";
text_view.setText( Html.fromHtml( str_links ) );
text_view.setMovementMethod(new TextViewClickMovement(this, context));
Links
Hope this helops! You can find code here.
A way cleaner and better solution, using native's Linkify library.
Example:
Linkify.addLinks(mTextView, Linkify.ALL);
If you're using Kotlin, I wrote a simple extension for this case:
/**
* Enables click support for a TextView from a [fullText] String, which one containing one or multiple URLs.
* The [callback] will be called when a click is triggered.
*/
fun TextView.setTextWithLinkSupport(
fullText: String,
callback: (String) -> Unit
) {
val spannable = SpannableString(fullText)
val matcher = Patterns.WEB_URL.matcher(spannable)
while (matcher.find()) {
val url = spannable.toString().substring(matcher.start(), matcher.end())
val urlSpan = object : URLSpan(fullText) {
override fun onClick(widget: View) {
callback(url)
}
}
spannable.setSpan(urlSpan, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
text = spannable
movementMethod = LinkMovementMethod.getInstance() // Make link clickable
}
Usage:
yourTextView.setTextWithLinkSupport("click on me: https://www.google.fr") {
Log.e("URL is $it")
}
An alternative, imho way simpler approach (for lazy developers like myself ;)
abstract class LinkAwareActivity : AppCompatActivity() {
override fun startActivity(intent: Intent?) {
if(Intent.ACTION_VIEW.equals(intent?.action) && onViewLink(intent?.data.toString(), intent)){
return
}
super.startActivity(intent)
}
// return true to consume the link (meaning to NOT call super.startActivity(intent))
abstract fun onViewLink(url: String?, intent: Intent?): Boolean
}
If required, you could also check for scheme / mimetype of the intent
You can do it more neatly using a simple library named Better-Link-Movement-Method.
TextView mTvUrl=findViewById(R.id.my_tv_url);
mTvUrl.setMovementMethod(BetterLinkMovementMethod.newInstance().setOnLinkClickListener((textView, url) -> {
if (Patterns.WEB_URL.matcher(url).matches()) {
//An web url is detected
return true;
}
else if(Patterns.PHONE.matcher(url).matches()){
//A phone number is detected
return true;
}
else if(Patterns.EMAIL_ADDRESS.matcher(url).matches()){
//An email address is detected
return true;
}
return false;
}));
Im using only textView, and set span for url and handle click.
I found very elegant solution here, without linkify - according to that I know which part of string I want to linkify
handle textview link click in my android app
in kotlin:
fun linkify(view: TextView, url: String, context: Context) {
val text = view.text
val string = text.toString()
val span = ClickSpan(object : ClickSpan.OnClickListener {
override fun onClick() {
// handle your click
}
})
val start = string.indexOf(url)
val end = start + url.length
if (start == -1) return
if (text is Spannable) {
text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
text.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.orange)),
start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
} else {
val s = SpannableString.valueOf(text)
s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
s.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.orange)),
start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
view.text = s
}
val m = view.movementMethod
if (m == null || m !is LinkMovementMethod) {
view.movementMethod = LinkMovementMethod.getInstance()
}
}
class ClickSpan(private val mListener: OnClickListener) : ClickableSpan() {
override fun onClick(widget: View) {
mListener.onClick()
}
interface OnClickListener {
fun onClick()
}
}
and usage: linkify(yourTextView, urlString, context)
This page solved my problem, but I had to figure something out myself. I was using android string resources to set the text of the TextView and obviously, they returned a CharSequence that has a link in between the text.
These were the resources:
<string name="license_agreement">By registering, you agree with our <b>Privacy Policy</b> and <b>Terms and Conditions</b></string>
<string name="sign_now">Already have an account? <b>Login</b></string>
I made changes to one of the code suggested. The code:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
// Make Licence agreement statements and login text clickable links
setLinkOnText(binding.txtLcAgree);
setLinkOnText(binding.signNow);
}
private void detectLinkClick(SpannableStringBuilder strBuilder, final URLSpan span) {
int start = strBuilder.getSpanStart(span);
int end = strBuilder.getSpanEnd(span);
int flags = strBuilder.getSpanFlags(span);
ClickableSpan clickable = new ClickableSpan() {
public void onClick(View view) {
// Do something with links retrieved from span.getURL(), to handle link click...
String clickedUrl = span.getURL();
switch (clickedUrl) {
case "#login_page":
startActivity(new Intent(RegistrationActivity.this, LoginActivity.class));
break;
case "http://www.privacy-options.com":
Uri link1 = Uri.parse("http://www.privacy-options.com");
startActivity(new Intent(Intent.ACTION_VIEW, link1));
break;
case "http://www.terms-and-conditions.com":
Uri link2 = Uri.parse("http://www.terms-and-conditions.com");
startActivity(new Intent(Intent.ACTION_VIEW, link2));
break;
default:
Log.w(getClass().getSimpleName(), "No action for this");
}
}
};
strBuilder.setSpan(clickable, start, end, flags);
strBuilder.removeSpan(span);
}
protected void setLinkOnText(TextView text) {
CharSequence sequence = text.getText();
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
for (URLSpan span : urls) {
detectLinkClick(strBuilder, span);
}
text.setText(strBuilder);
text.setMovementMethod(LinkMovementMethod.getInstance());
}
The links retrieved from span.getUrl() was the initial link I set in the string resource. And since the text in the TextView was already in link format, I just simply used that text in the SpannableStringBuilder.
For The amazing answer by Zane Claes on top. Simply add the below code before calling strBuilder.getSpans() works great for me.
Linkify.addLinks(strBuilder, Linkify.ALL)
You need to create a class that extends LinkMovementMethod and override the onTouchEvent() function. I duplicated some code from LinkMovementMethod's method to get the link.
#Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event)
{
int action = event.getAction();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] links = buffer.getSpans(off, off, ClickableSpan.class);
if (links.length != 0) {
String url = ((URLSpan) links[0]).getURL());
} else {
return super.onTouchEvent(widget, buffer, event);
}
}
return super.onTouchEvent(widget, buffer, event);
}
I am trying to make an ordered list from XML in a textview. This list would be bulleted and properly justified with subheadings. Unfortunately, it seems that the support for this in the xml is minimal. I have tried the following in strings.xml:
<ol>
<li> item 1\n
<li>sub-item1\n</li>
<li>sub-item2\n</li>
<li>item2\n</li>
<li>item3</li>
</ol>
with various permutations having ol around each item etc etc. The result typically shows subitem2 and item 2 being indented away from the bullet. I have been really scratching my head on this one. Any guidance on this would be great.
First, create a Custom Tag handler class:
package com.thecitybank.myca.ui;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.style.BulletSpan;
import android.text.style.LeadingMarginSpan;
import android.util.Log;
import org.xml.sax.XMLReader;
import java.util.Stack;
public class MyTagHandler implements Html.TagHandler {
private static final String OL_TAG = "ol";
private static final String UL_TAG = "ul";
private static final String LI_TAG = "li";
private static final int INDENT_PX = 10;
private static final int LIST_ITEM_INDENT_PX = INDENT_PX * 2;
private static final BulletSpan BULLET_SPAN = new BulletSpan(INDENT_PX);
private final Stack<ListTag> lists = new Stack<ListTag>();
#Override
public void handleTag(final boolean opening, final String tag, final Editable output, final XMLReader xmlReader) {
if (UL_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <ul>
lists.push(new Ul());
} else { // handle </ul>
lists.pop();
}
} else if (OL_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <ol>
lists.push(new Ol()); // use default start index of 1
} else { // handle </ol>
lists.pop();
}
} else if (LI_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <li>
lists.peek().openItem(output);
} else { // handle </li>
lists.peek().closeItem(output, lists.size());
}
} else {
Log.d("TagHandler", "Found an unsupported tag " + tag);
}
}
/**
* Abstract super class for {#link Ul} and {#link Ol}.
*/
private abstract static class ListTag {
/**
* Opens a new list item.
*
* #param text
*/
public void openItem(final Editable text) {
if (text.length() > 0 && text.charAt(text.length() - 1) != '\n') {
text.append("\n");
}
final int len = text.length();
text.setSpan(this, len, len, Spanned.SPAN_MARK_MARK);
}
/**
* Closes a list item.
*
* #param text
* #param indentation
*/
public final void closeItem(final Editable text, final int indentation) {
if (text.length() > 0 && text.charAt(text.length() - 1) != '\n') {
text.append("\n");
}
final Object[] replaces = getReplaces(text, indentation);
final int len = text.length();
final ListTag listTag = getLast(text);
final int where = text.getSpanStart(listTag);
text.removeSpan(listTag);
if (where != len) {
for (Object replace : replaces) {
text.setSpan(replace, where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
protected abstract Object[] getReplaces(final Editable text, final int indentation);
/**
* Note: This knows that the last returned object from getSpans() will be the most recently added.
*
* #see Html
*/
private ListTag getLast(final Spanned text) {
final ListTag[] listTags = text.getSpans(0, text.length(), ListTag.class);
if (listTags.length == 0) {
return null;
}
return listTags[listTags.length - 1];
}
}
/**
* Class representing the unordered list ({#code <ul>}) HTML tag.
*/
private static class Ul extends ListTag {
#Override
protected Object[] getReplaces(final Editable text, final int indentation) {
// Nested BulletSpans increases distance between BULLET_SPAN and text, so we must prevent it.
int bulletMargin = INDENT_PX;
if (indentation > 1) {
bulletMargin = INDENT_PX - BULLET_SPAN.getLeadingMargin(true);
if (indentation > 2) {
// This get's more complicated when we add a LeadingMarginSpan into the same line:
// we have also counter it's effect to BulletSpan
bulletMargin -= (indentation - 2) * LIST_ITEM_INDENT_PX;
}
}
return new Object[]{
new LeadingMarginSpan.Standard(LIST_ITEM_INDENT_PX * (indentation - 1)),
new BulletSpan(bulletMargin)
};
}
}
/**
* Class representing the ordered list ({#code <ol>}) HTML tag.
*/
private static class Ol extends ListTag {
private int nextIdx;
/**
* Creates a new {#code <ul>} with start index of 1.
*/
public Ol() {
this(1); // default start index
}
/**
* Creates a new {#code <ul>} with given start index.
*
* #param startIdx
*/
public Ol(final int startIdx) {
this.nextIdx = startIdx;
}
#Override
public void openItem(final Editable text) {
super.openItem(text);
text.append(Integer.toString(nextIdx++)).append(". ");
}
#Override
protected Object[] getReplaces(final Editable text, final int indentation) {
int numberMargin = LIST_ITEM_INDENT_PX * (indentation - 1);
if (indentation > 2) {
// Same as in ordered lists: counter the effect of nested Spans
numberMargin -= (indentation - 2) * LIST_ITEM_INDENT_PX;
}
return new Object[]{new LeadingMarginSpan.Standard(numberMargin)};
}
}
}
Then add a string in your string.xml as done below:
<string name="change_password_note"><![CDATA[<ol><li>Your password should contain at least one character of a-z, A-Z and 0-9. No special character is allowed.</li> <li>Please do not use any of your last three passwords.</li> <li>Please do not enter your User ID as password.</li> <li>Password minimum of 8 and maximum of 20 characters.</li></ol>]]></string>
Lastly, set text into your TextView as below:
txtNotesDescription.setText(Html.fromHtml(getString(R.string.change_password_note),null,new MyTagHandler()));
This worked for me. You can use un-ordered list by using the (ul) tag.
<string name="accessibility_service_instructions">
1. Enable TalkBack (Settings -> Accessibility -> TalkBack).
\n\n2. Enable Explore-by-Touch (Settings -> Accessibility -> Explore by Touch).
\n\n3. Touch explore the Clock application and the home screen.
\n\n4. Go to the Clock application and change the time of an alarm.
\n\n5. Enable ClockBack (Settings -> Accessibility -> ClockBack).
\n\n6. Go to the Clock application and change an alarm.
\n\n7. Set the ringer to vibration mode and change an alarm.
\n\n8. Set the ringer to muted mode and change an alarm.
</string>
Html List tag not working in android TextView. This is my string content:
String str="A dressy take on classic gingham in a soft, textured weave of stripes that resembles twill. Take a closer look at this one.<ul><li>Trim, tailored fit for a bespoke feel</li><li>Medium spread collar, one-button mitered barrel cuffs</li><li>Applied placket with genuine mother-of-pearl buttons</li><li>;Split back yoke, rear side pleats</li><li>Made in the U.S.A. of 100% imported cotton.</li></ul>";
I loaded it in a text view like this:
textview.setText(Html.fromHtml(str));
The output looks like a paragraph. What can I do? Is there any solution for it?
Edit:
webview.loadData(str,"text/html","utf-8");
As you can see in the Html class source code, Html.fromHtml(String) does not support all HTML tags. In this very case, <ul> and <li> are not supported.
From the source code I have built a list of allowed HTML tags:
br
p
div
em
b
strong
cite
dfn
i
big
small
font
blockquote
tt
monospace
a
u
sup
sub
So you better use WebView and its loadDataWithBaseURL method. Try something like this:
String str="<html><body>A dressy take on classic gingham in a soft, textured weave of stripes that resembles twill. Take a closer look at this one.<ul><li>Trim, tailored fit for a bespoke feel</li><li>Medium spread collar, one-button mitered barrel cuffs</li><li>Applied placket with genuine mother-of-pearl buttons</li><li>;Split back yoke, rear side pleats</li><li>Made in the U.S.A. of 100% imported cotton.</li></ul></body></html>";
webView.loadDataWithBaseURL(null, str, "text/html", "utf-8", null);
I was having the same problem, and what I did is overriding the default TagHandler. This one worked for me.
public class MyTagHandler implements TagHandler {
boolean first = true;
String parent = null;
int index = 1;
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if (tag.equals("ul")) {
parent = "ul";
} else if (tag.equals("ol")) {
parent = "ol";
}
if (tag.equals("li")) {
if (parent.equals("ul")) {
if (first) {
output.append("\n\t•");
first = false;
} else {
first = true;
}
} else{
if (first) {
output.append("\n\t"+index+". ");
first = false;
index++;
} else {
first = true;
}
}
}
}
}
and for displaying the text...
myTextView.setText(Html.fromHtml("<ul><li>I am an Android developer</li><li>Another Item</li></ul>", null, new MyTagHandler()));
[Edit]
Kuitsi has also posted an really good library that does the same, got it from this SO link.
Full sample project is located at https://bitbucket.org/Kuitsi/android-textview-html-list.
Sample picture is available at https://kuitsi.bitbucket.io/stackoverflow3150400_screen.png
This solution is closest to masha's answer. Some code is also taken from inner class android.text.Html.HtmlToSpannedConverter. It supports nested ordered and unordered lists but too long texts in ordered lists are still aligned with item number rather than text. Mixed lists (ol and ul) needs some work too. Sample project contains implementation of Html.TagHandler which is passed to Html.fromHtml(String, ImageGetter, TagHandler).
Edit: For wider HTML tag support, https://github.com/NightWhistler/HtmlSpanner might also be worth trying.
A small fix to Aman Guatam code. The function above has problem of rendering newline character. For example: if before <li> tag is a <p> tag, 2 newline characters are rendered. Here is upgraded code:
import org.xml.sax.XMLReader;
import android.text.Editable;
import android.text.Html.TagHandler;
public class ListTagHandler implements TagHandler {
boolean first = true;
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
// TODO Auto-generated method stub
if (tag.equals("li")) {
char lastChar = 0;
if (output.length() > 0)
lastChar = output.charAt(output.length() - 1);
if (first) {
if (lastChar == '\n')
output.append("\t• ");
else
output.append("\n\t• ");
first = false;
} else {
first = true;
}
}
}
}
WARNING
As of Android 7 android.text.Html actually supports li and ul tags and uses a basic BulletSpan(), which means in the latest versions of Android the Html.TagHandlersolutions posted here will be ignored
Make sure your code handles this change. In case you want a BulletSpan with a larger gap than the default, you can can replace it with another span:
val html = SpannableStringBuilder(HtmlCompat.fromHtml(source, HtmlCompat.FROM_HTML_MODE_COMPACT))
val bulletSpans = html.getSpans<BulletSpan>(0, html.length)
bulletSpans.forEach {
val spanStart = html.getSpanStart(it)
val spanEnd = html.getSpanEnd(it)
html.removeSpan(it)
val bulletSpan = BulletSpan(gapWidthInDp, context.getColor(R.color.textColorBlack))
html.setSpan(bulletSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
Different solution using LeadingMarginSpan. Handles ordered and unordered lists as well as nesting.
public class ListTagHandler implements TagHandler
{
private int m_index = 0;
private List< String > m_parents = new ArrayList< String >( );
#Override
public void handleTag( final boolean opening, final String tag, Editable output, final XMLReader xmlReader )
{
if( tag.equals( "ul" ) || tag.equals( "ol" ) || tag.equals( "dd" ) )
{
if( opening )
{
m_parents.add( tag );
}
else m_parents.remove( tag );
m_index = 0;
}
else if( tag.equals( "li" ) && !opening ) handleListTag( output );
}
private void handleListTag( Editable output )
{
if( m_parents.get(m_parents.size()-1 ).equals( "ul" ) )
{
output.append( "\n" );
String[ ] split = output.toString( ).split( "\n" );
int lastIndex = split.length - 1;
int start = output.length( ) - split[ lastIndex ].length( ) - 1;
output.setSpan( new BulletSpan( 15 * m_parents.size( ) ), start, output.length( ), 0 );
}
else if( m_parents.get(m_parents.size()-1).equals( "ol" ) )
{
m_index++ ;
output.append( "\n" );
String[ ] split = output.toString( ).split( "\n" );
int lastIndex = split.length - 1;
int start = output.length( ) - split[ lastIndex ].length( ) - 1;
output.insert( start, m_index + ". " );
output.setSpan( new LeadingMarginSpan.Standard( 15 * m_parents.size( ) ), start, output.length( ), 0 );
}
}
}
If you only need to format a list, keep it simple and copy/paste a unicode character in your TextView to achieve the same result.
• Unicode Character 'BULLET' (U+2022)
I came here looking for TagHandler implementations. Both Truong Nguyen and Aman Guatam answers are very nice, but I needed a mixed version of both: I needed my solution not to overformat it and to be able to ressolve <ol> tags, since I'm parsing something like <h3>title</h3><ol><li>item</li><li>item</li><li>item</li></ol>.
Here's my solution.
import org.xml.sax.XMLReader;
import android.text.Editable;
import android.text.Html.TagHandler;
public class MyTagHandler implements TagHandler {
boolean first = true;
String parent = null;
int index = 1;
public void handleTag(final boolean opening, final String tag,
final Editable output, final XMLReader xmlReader) {
if (tag.equals("ul")) {
parent = "ul";
index = 1;
} else if (tag.equals("ol")) {
parent = "ol";
index = 1;
}
if (tag.equals("li")) {
char lastChar = 0;
if (output.length() > 0) {
lastChar = output.charAt(output.length() - 1);
}
if (parent.equals("ul")) {
if (first) {
if (lastChar == '\n') {
output.append("\t• ");
} else {
output.append("\n\t• ");
}
first = false;
} else {
first = true;
}
} else {
if (first) {
if (lastChar == '\n') {
output.append("\t" + index + ". ");
} else {
output.append("\n\t" + index + ". ");
}
first = false;
index++;
} else {
first = true;
}
}
}
}
}
Note that, since we are resetting the index value whenever a new list starts, it WILL NOT work if you nest lists like in <ol><li>1<ol><li>1.1</li><li>1.2</li></ol><li>2</li></ol>11.11.22
With that code, you would get 1, 1, 2, 3 instead of 1, 1, 2, 2.
You can simply replace the "li" with unicodes
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if (tag.equalsIgnoreCase("li")) {
if (opening) {
output.append("\u2022 ");
} else {
output.append("\n");
}
}
}
Sure, there ise a way of showing bullets in Android TextView. You can replace <li> tags with (which is HTML code for bullet).
If you want to try other list icons, use the preferred one from the table is this link;
http://www.ascii-code.com/
You can use Html.TagHandler. Below can be used for kotlin
class UlTagHandler : Html.TagHandler {
override fun handleTag(
opening: Boolean, tag: String, output: Editable,
xmlReader: XMLReader
) {
if (tag == "ul" && !opening) output.append("\n")
if (tag == "li" && opening) output.append("\n\t•")
}
}
and
textView.setText(Html.fromHtml(myHtmlText, null, UlTagHandler()));
Lord Voldermort's answer is a good starting point. However I required ol tag to display ordered list 1. 2. 3. .... instead of bullets. Also, nested tags need special handling to work properly.
In my code, I have maintained stack(parentList) to keep track of opened and closed ul and ol tags and also to know the current open tag.
Also, a levelWiseCounter is used to maintain different counts in case of nested ol tags.
myTextView.setText(Html.fromHtml("your string", null, new CustomTagHandler()));
.
.
.
private static class CustomTagHandler implements TagHandler
{
int level = 0;
private LinkedList<Tag> parentList = new LinkedList<DetailFragment.CustomTagHandler.Tag>();
private HashMap<Integer, Integer> levelWiseCounter = new HashMap<Integer, Integer>();
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader)
{
if (tag.equalsIgnoreCase("ul") || tag.equalsIgnoreCase("ol"))
{
if (opening)
{
if (tag.equalsIgnoreCase("ul"))
{
parentList.push(Tag.UL);
}
else
{
parentList.push(Tag.OL);
}
level++;
}
else
{
if (!parentList.isEmpty())
{
parentList.pop();
//remove counter at that level, in any present.
levelWiseCounter.remove(level);
}
level--;
if (level < 0)
{
level = 0;
}
}
}
else if (tag.equalsIgnoreCase("li"))
{
if (opening && level > 0)
{
//new line check
int length = output.toString().length();
if (length > 0 && (output.toString().charAt(length - 1) == '\n'))
{
}
else
{
output.append("\n");
}
//add tabs as per current level of li
for (int i = 0; i < level; i++)
{
output.append("\t");
}
// append dot or numbers based on parent tag
if (Tag.UL == parentList.peek())
{
output.append("•");
}
else
{
//parent is OL. Check current level and retreive counter from levelWiseCounter
int counter = 1;
if (levelWiseCounter.get(level) == null)
{
levelWiseCounter.put(level, 1);
}
else
{
counter = levelWiseCounter.get(level) + 1;
levelWiseCounter.put(level, counter);
}
output.append(padInt(counter) + ".");
}
//trailing tab
output.append("\t");
}
}
}
/**
* Add padding so that all numbers are aligned properly. Currently supports padding from 1-99.
*
* #param num
* #return
*/
private static String padInt(int num)
{
if (num < 10)
{
return " " + num;
}
return "" + num;
}
private enum Tag
{
UL, OL
}
}
How about the next code (based on this link) :
public class TextViewHtmlTagHandler implements TagHandler
{
/**
* Keeps track of lists (ol, ul). On bottom of Stack is the outermost list
* and on top of Stack is the most nested list
*/
Stack<String> lists =new Stack<String>();
/**
* Tracks indexes of ordered lists so that after a nested list ends
* we can continue with correct index of outer list
*/
Stack<Integer> olNextIndex =new Stack<Integer>();
/**
* List indentation in pixels. Nested lists use multiple of this.
*/
private static final int indent =10;
private static final int listItemIndent =indent*2;
private static final BulletSpan bullet =new BulletSpan(indent);
#Override
public void handleTag(final boolean opening,final String tag,final Editable output,final XMLReader xmlReader)
{
if(tag.equalsIgnoreCase("ul"))
{
if(opening)
lists.push(tag);
else lists.pop();
}
else if(tag.equalsIgnoreCase("ol"))
{
if(opening)
{
lists.push(tag);
olNextIndex.push(Integer.valueOf(1)).toString();// TODO: add support for lists starting other index than 1
}
else
{
lists.pop();
olNextIndex.pop().toString();
}
}
else if(tag.equalsIgnoreCase("li"))
{
if(opening)
{
if(output.length()>0&&output.charAt(output.length()-1)!='\n')
output.append("\n");
final String parentList=lists.peek();
if(parentList.equalsIgnoreCase("ol"))
{
start(output,new Ol());
output.append(olNextIndex.peek().toString()+". ");
olNextIndex.push(Integer.valueOf(olNextIndex.pop().intValue()+1));
}
else if(parentList.equalsIgnoreCase("ul"))
start(output,new Ul());
}
else if(lists.peek().equalsIgnoreCase("ul"))
{
if(output.charAt(output.length()-1)!='\n')
output.append("\n");
// Nested BulletSpans increases distance between bullet and text, so we must prevent it.
int bulletMargin=indent;
if(lists.size()>1)
{
bulletMargin=indent-bullet.getLeadingMargin(true);
if(lists.size()>2)
// This get's more complicated when we add a LeadingMarginSpan into the same line:
// we have also counter it's effect to BulletSpan
bulletMargin-=(lists.size()-2)*listItemIndent;
}
final BulletSpan newBullet=new BulletSpan(bulletMargin);
end(output,Ul.class,new LeadingMarginSpan.Standard(listItemIndent*(lists.size()-1)),newBullet);
}
else if(lists.peek().equalsIgnoreCase("ol"))
{
if(output.charAt(output.length()-1)!='\n')
output.append("\n");
int numberMargin=listItemIndent*(lists.size()-1);
if(lists.size()>2)
// Same as in ordered lists: counter the effect of nested Spans
numberMargin-=(lists.size()-2)*listItemIndent;
end(output,Ol.class,new LeadingMarginSpan.Standard(numberMargin));
}
}
else if(opening)
Log.d("TagHandler","Found an unsupported tag "+tag);
}
private static void start(final Editable text,final Object mark)
{
final int len=text.length();
text.setSpan(mark,len,len,Spanned.SPAN_MARK_MARK);
}
private static void end(final Editable text,final Class<?> kind,final Object... replaces)
{
final int len=text.length();
final Object obj=getLast(text,kind);
final int where=text.getSpanStart(obj);
text.removeSpan(obj);
if(where!=len)
for(final Object replace : replaces)
text.setSpan(replace,where,len,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return;
}
private static Object getLast(final Spanned text,final Class<?> kind)
{
/*
* This knows that the last returned object from getSpans()
* will be the most recently added.
*/
final Object[] objs=text.getSpans(0,text.length(),kind);
if(objs.length==0)
return null;
return objs[objs.length-1];
}
private static class Ul
{
}
private static class Ol
{
}
}
I had the problem, that I always got an empty line after a list with #Kuitsis solution. I added a few lines in handleTag() and now the empty lines are gone:
#Override
public void handleTag(final boolean opening, final String tag, final Editable output, final XMLReader xmlReader) {
if (UL_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <ul>
lists.push(new Ul());
} else { // handle </ul>
lists.pop();
if (output.length() > 0 && output.charAt(output.length() - 1) == '\n') {
output.delete(output.length() - 1, output.length());
}
}
} else if (OL_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <ol>
lists.push(new Ol()); // use default start index of 1
} else { // handle </ol>
lists.pop();
if (output.length() > 0 && output.charAt(output.length() - 1) == '\n') {
output.delete(output.length() - 1, output.length());
}
}
} else if (LI_TAG.equalsIgnoreCase(tag)) {
if (opening) { // handle <li>
lists.peek().openItem(output);
} else { // handle </li>
lists.peek().closeItem(output, lists.size());
}
} else {
Log.d("TagHandler", "Found an unsupported tag " + tag);
}
}
this is a confirmation to what kassim has stated. there is fragmentation. i found how to resolve this. i have to rename <li> and ul to a custom tag. so:
myHTML.replaceAll("</ul>","</customTag>").replaceAll("<ul>","<customTag>");
//likewise for li
then in my handler i can look for that customTag (which does nothing) and make it do something.
//now my handler can handle the customtags. it was ignoring them after nougat.
public class UlTagHandler implements Html.TagHandler {
//for ul in nougat and up this tagHandler is completely ignored
#Override
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if (tag.equals("customtag2") && opening)
output.append("\n\t\u25CF\t");
if (tag.equals("customtag2") && !opening)
output.append("\n");
}
}
this should make it work for all versions of android.