I have some text with a link in a TextView. Now I want that the browser open the link if the user click on it. My TextView looks like this:
<string name="Info">Go to Google</string>
<TextView
android:id="#+id/Info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/OptionMarginBottom"
android:autoLink="web"
android:linksClickable="true"
android:text="#string/Info" />
The Link is displayed correct in blue but I can not click on it. Why is that?
use this method
public static void addLink(TextView textView, String patternToMatch,
final String link) {
Linkify.TransformFilter filter = new Linkify.TransformFilter() {
#Override public String transformUrl(Matcher match, String url) {
return link;
}
};
Linkify.addLinks(textView, Pattern.compile(patternToMatch), null, null,
filter);
}
and use as
addLink(text, "^Android", "http://abhiandroidinfo.blogspot.in");
Use Linkify on your TextView
Linkify.addLinks(yourTextviewObject, Linkify.WEB_URLS);
Linkify take a piece of text and a regular expression and turns all of
the regex matches in the text into clickable links.
Helper Method:
public static void addLinks(TextView textView, String linkThis, String toThis) {
Pattern pattern = Pattern.compile(linkThis);
String scheme = toThis;
android.text.util.Linkify.addLinks(textView, pattern, scheme, new MatchFilter() {
#Override
public boolean acceptMatch(CharSequence s, int start, int end) {
return true;
}
}, new TransformFilter() {
#Override
public String transformUrl(Matcher match, String url) {
return "";
}
});
}
Now use like Below:
String weblink = "WebsiteName";
String url = course.getString(TAG_Info);
TextView txtInfo= (TextView) findViewById(R.id.Info);
txtInfo.setText(userCanSeeThis);
addLinks(txtInfo, weblink, url);
Easier method is to make a string and add Link Text
and in the xml file, make the textView:
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:text="#string/string_with_link" />
Related
I am having a edit text which is behaving like feeds in face book. So whenever i post something like "www.google.com" it is showing as hyperlink, But at the same time whenever i post something like "abcd.abcd" , it is also showing me as a hyper link. I want to show my post as link only when i add "http" or "www" , How to achieve this. Thanks in advance
<EditText
android:id="#+id/etFeedsText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="50dp"
android:maxLength="2000"
android:layout_marginBottom="25.8dp"
android:layout_marginLeft="14dp"
android:layout_marginTop="8.3dp"
android:hint="#string/enter_your_post"
android:background="#color/white"
android:inputType="textMultiLine|textNoSuggestions"
android:textColor="#color/feeds_text"
android:textSize="13.3sp" />
You can compare your text & can find out if its a valid URL or not by this method,
/**
* This is used to check the given URL is valid or not.
* #param url
* #return true if url is valid, false otherwise.
*/
private boolean isValidUrl(String url) {
Pattern p = Patterns.WEB_URL;
Matcher m = p.matcher(url.toLowerCase());
return m.matches();
}
If the text is not an URL then remove the underline from bottom like,
if(!isValidUrl(yourUrl)){
stripUnderlines(TextView textView)
}
private void stripUnderlines(TextView textView) {
Spannable s = new SpannableString(textView.getText());
URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
for (URLSpan span: spans) {
int start = s.getSpanStart(span);
int end = s.getSpanEnd(span);
s.removeSpan(span);
span = new URLSpanNoUnderline(span.getURL());
s.setSpan(span, start, end, 0);
}
textView.setText(s);
}
It requires a customized version of URLSpan which doesn't enable the TextPaint's "underline" property:
private class URLSpanNoUnderline extends URLSpan {
public URLSpanNoUnderline(String url) {
super(url);
}
#Override public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
}
Hope this help!
Just add this to your Edittext
Linkify.addLinks(etFeedsText, Linkify.WEB_URLS);
This will consider only valid URLs.
Also you can use a textview, if you are just displaying the data. Edittext is not necessary.
I'm integrating Firebase to support Deeplink feature in app. I have seen in one of screen-example suggested(PFA) here that we can add our own custom text instead of display Deep link URL.
I have tried to update but that did not help. How to do that, Any suggestion?
My guess is that you are using a UITextView for when the user enters text (in iOS). Here is how to accomplish that in Swift:
class ViewController: UIViewController {
#IBOutlet weak var textView: UITextView!
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buttonPress(_ sender: Any) {
let range = textView.selectedRange
let linkString = NSMutableAttributedString(string: textView.text)
linkString.addAttribute(NSLinkAttributeName, value: textField.text ?? "", range: range)
textView.attributedText = linkString
}
}
extension ViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
UIApplication.shared.open(URL, options: [:], completionHandler: nil)
return false
}
}
In Android, I found a couple of SO answers that seem to handle the topic well:
Make a hyperlink textview in android
From user370305:
Try this, and let me know what happen..
TextView textView =(TextView)findViewById(R.id.textView);
textView.setClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='http://www.google.com'> Google </a>";
textView.setText(Html.fromHtml(text));
Put html link in edittext android
From RobinHood:
Put your html in a string#
<string url="link"><a href="http://www.google.com">Google</a></string>
set String to editText#
youredittext.setText(Html.fromHtml(getResources().getString(R.string.url)));
For click, set LinkMovementMethod with necessary action#
youredittext.setMovementMethod(LinkMovementMethod.getInstance());
If you are trying to accomplish this in HTML, then use an anchor (a) tag:
<p>Click on this Link</p>
I have done the same thing in one of my apps. Please follow below code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/margin"
tools:context="tdsolutions.com.clickabletext.MainActivity">
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World this text" />
</LinearLayout>
Pass your Textview to below method(setClickableText):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.text);
setClickableText(text);
}
private void setClickableText(TextView textView) {
String text = "this"; // the text you want to mark as a link
SpannableString ss = new SpannableString(textView.getText());// full text
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.parseColor("#91ca46"));//link text color
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
//What ever the code you want when click on text goes here
Toast.makeText(MainActivity.this,"you clicked",Toast.LENGTH_LONG).show();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
};
int start = textView.getText().toString().indexOf(text);
int length = start + text.length();
ss.setSpan(clickableSpan, start, length, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
ss.setSpan(fcs, start, length, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);
}
Or you can use below code:
Add the text view as below, change whatever the attributes as you wish.
<TextView
android:id="#+id/textView"
android:layout_centerInParent="true"
android:linksClickable="true"
android:textColorLink="#00f"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
then add below code:
TextView textView = (TextView) findViewById(R.id.textView);
Spanned result;
String html = "Hi sweetheart go to this link";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(html ,Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(html);
}
textView.setText(result);
textView. setMovementMethod(LinkMovementMethod.getInstance());
please make sure when you add links replace them with html tags as I did in the example String html = "Hi sweetheart go to this link";
I have a TextView in listview which can have 2+ links. I had gone through to this SO link to capture the event of a TextView but this is not working for a list view.
Here is my code:
getView method
if(ann.message.contains("<a href=")){
setTextViewHTML(holder.announcement, ann.message);
}
methods to make text clickable
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...
Log.i("YES-5.0", span.getURL());
}
};
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);
}
This is my TextView:
<TextView
android:id="#+id/textViewAnnouncementMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="4dp"
android:focusable="false"
android:textColor="#android:color/black"
android:maxLines="5"
android:text="#string/message"
android:textSize="16sp"/>
I have tried with all the combinations of following attributes of `TextView' but still no success:
android:autoLink="all"
android:clickable="true"
android:linksClickable="true"
Have you set your movement method on your TextView? Also, if your link comes as an a href tag, you can just use Html.fromHtml to build your Spannable for you. For example:
TextView mView = (TextView) findViewById(R.id.text1);
mView.setMovementMethod(LinkMovementMethod.getInstance());
mView.setText(Html.fromHtml(YOUR_LINK_STRING));
if you use a XML Layout for your textview and that your clickable links all start with http:// il devrait etre suffisant d'utiliser les attributs suivants:
<TextView
...
android:autoLink="all"
android:linksClickable="true"
android:textColorLink="#color/colorAccent" />
autoLink all means that all mailAdress, http link and phone numbers will be clickable. Just give a look at official documentation for further details: http://developer.android.com/reference/android/text/util/Linkify.html#ALL
I solved my problem by adding following line before calling setTextViewHTML():
holder.announcement.setMovementMethod(LinkMovementMethod.getInstance());
So now my getView() method looks like:
if(ann.message.contains("<a href=")){
holder.announcement.setMovementMethod(LinkMovementMethod.getInstance());
setTextViewHTML(holder.announcement, ann.message);
}
I am using a text view in my aap, which is having plane text as well as a hyperlink. Now when I click on hyperlink then link open with default browser. But in actual I dont want to open default browser. Actually I want to register OnClickListener on hyperlink and want to perform other.
I searched on internet and I got this solution...
Control onclicklistener in autolink enabled textview
But this is not helpful for me.
Anyone can tell me that how I can perform this.
Thanks in advance
you can use a Spannable object
final Spannable span = new SpannableString(text);
span.setSpan(new ClickableSpan() {
#Override
public void onClick(View v) {
}
}, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
where text is your hyperlink
Remove android:autoLink="web" if this property setted into XML.
TextView textView =(TextView)findViewById(R.id.textView);
textView.setClickable(true);
when you want to open in browser use this code
textView.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='http://www.google.com'> Google </a>";
textView.setText(Html.fromHtml(text));
if you want to perform some operation register onclick listener for textview and perform.
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Try doing this add
in your
main.xml
<TextView
android:id="#+id/yourTVID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="performSomeAction" />
in your SomeActivity.java
public void performSomeAction( View v){
//Perform your action
}
Try this, it should solve your problem. This method will return a Spannable String which have part of it clickable.
Before calling the below method you should Create CharSequence from the String then convert it to Spannable
CharSequence charSequencce = testView.getText();
Spannable spannable = (Spannable) charSequencce;
public SpannableStringBuilder addClickToPartsOfString(Spannable charSequence, String[] stringsToAddClick, final OnHyperLinkClickListener onClickListener) {
SpannableStringBuilder ssb = new SpannableStringBuilder(charSequence);
for(final String s : stringsToAddClick) {
int index1 = charSequence.toString().indexOf(s);
int index2 = (s.length() + index1);
ssb.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
onClickListener.onClick(s);
}
}, index1, index2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return ssb;
}
I've just made a library aiming to simplify this. See Textoo. You can achieve the same with code like:
TextView locNotFound = Textoo
.config((TextView) findViewById(R.id.view_location_disabled))
.addLinksHandler(new LinksHandler() {
#Override
public boolean onClick(View view, String url) {
if ("internal://settings/location".equals(url)) {
Intent locSettings = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(locSettings);
return true;
} else {
return false;
}
}
})
.apply();
Internally the library converts existing links in your textview / string resources (android system parse html links in string resources into Span for you already) into custom ClickableSpan and capture clicks into calls to your handlers.
This relieve you from having to calculate and hard coding the position of clickable spans to add. Thus make it easier to externalize your text into string resources and better for localization.
I have text view and I want to set-text as link to direct the site but
the problem is that I cannot click:
Grades = (TextView) findViewById(R.id.textView9);
Grades.setText(Html.fromHtml(course.getString(TAG_Grade)));
Grades.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
WebView webView; webView.setWebViewClient(new WebViewClient()
{
}webView.loadUrl(course.getString(TAG_Grade)); });
And the xml:
<TextView
android:id="#+id/textView9"
android:layout_marginLeft="110dp"
android:layout_marginTop="365dp"
android:textColor="#000"
android:textSize="14sp"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:autoLink="web"
android:onClick="onClick"
/>
Knowing that course.getString(TAG_Grade) will get the url from db but it does not work
What is the problem?
You are trying to Linkify it after the view is clicked, removed the Linkify from within the onClick.
Your going about it the wrong way.
Try this:
String userCanSeeThis = "Your Website Name";
String url = course.getString(TAG_Grade);
TextView grades = (TextView) findViewById(R.id.textView9);
grades.setText(userCanSeeThis);
addLinks(Grades, userCanSeeThis, url);
Using this helper method:
/**
* #param textView
* textView who's text you want to change
* #param linkThis
* a regex of what text to turn into a link
* #param toThis
* the url you want to send them to
*/
public static void addLinks(TextView textView, String linkThis, String toThis) {
Pattern pattern = Pattern.compile(linkThis);
String scheme = toThis;
android.text.util.Linkify.addLinks(textView, pattern, scheme, new MatchFilter() {
#Override
public boolean acceptMatch(CharSequence s, int start, int end) {
return true;
}
}, new TransformFilter() {
#Override
public String transformUrl(Matcher match, String url) {
return "";
}
});
}
Also if you set the onClickListener in your code with grades.setOnClickListener then your don't need android:onClick="" in your XML
Used this android:clickable="true"
<TextView
android:id="#+id/textView9"
android:layout_marginLeft="110dp"
android:layout_marginTop="365dp"
android:textColor="#000"
android:textSize="14sp"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:autoLink="web"
android:onClick="onClick"
/>
Instead of using Linkify i would prefer the below line:
Html.fromHtml(course.getString(TAG_Grade));
TextView myWebSite = new TextView(this);
myWebSite .setText("http://www.google.com/");
Linkify.addLinks(myWebSite , Linkify.WEB_URLS);
You have received enough answers regarding Linkify, but there is one more subtile error crawling in your code:
You are mistaking the attribute his android:onClick with the method onClick of an View.onClickListener:
The attribute android:onClick works as followed:
Name of the method in this View's context to invoke when the view is
clicked. This name must correspond to a public method that takes
exactly one parameter of type View. For instance, if you specify
android:onClick="sayHello", you must declare a public void
sayHello(View v) method of your context (typically, your Activity).
As for the onClick-method provided by the View.onClickListener-interface:
view.setOnClickListener(...)
Register a callback to be invoked when this view is
clicked. If this view is not clickable, it becomes clickable.
Which will allow you to override the function :
public abstract void onClick (View v)
which is called when a view has been clicked.