How to assign multiple string resources to a single textview? - android

I have created 3 strings in string resources. Every string has an external link in it. Basically I am trying to put one sentence in a TextView which has 3 outside links in it. Please tell how to do this in Android.
If we can assign multiple string through XML only that will be best.

If you want to combine your 3 links and make them clickable you can try this :
<string name="combined_links"><![CDATA[ my link one my link two my link three]]></string>
String sentence = getString(R.string.combined_links, getString(R.string.link_one), getString(R.string.link_two), getString(R.string.link_three))

You have to use Spannable, here is example below, have a look
ClickableSpan linkClick = new ClickableSpan() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Link Click",
Toast.LENGTH_SHORT).show();
view.invalidate();
}
#Override
public void updateDrawState(TextPaint ds) {
if (textView.isPressed()) {
ds.setColor(Color.BLUE);
} else {
ds.setColor(Color.RED);
}
textView.invalidate();
}
};
textView.setHighlightColor(Color.TRANSPARENT);
Spannable spannableString = new SpannableString("Link in TextView");
spannableString.setSpan(linkClick, 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString, TextView.BufferType.SPANNABLE);
textView.setMovementMethod(LinkMovementMethod.getInstance());
In this, String Link in TextView only "LINK" is clickable

Related

How to make a variable string containing buttons

I want make a layout like this .
Initially we arranged buttons and text in succession.
However, if there is a line break, it will not be displayed as desired.
Do you know the library or the means to realize this?
My English is still not so good, though, Sorry.
String str="text1 button1 text2 button2 etc.";
SpannableString spanString=new SpannableString(str);
//You can use SpannableStringBuilder also
ClickableSpan buttonSpan1 = new ClickableSpan() {
#Override
public void onClick(View view) {
// Do something
}
};
ClickableSpan buttonSpan2 = new ClickableSpan() {
#Override
public void onClick(View view) {
// Do something
}
};
spanString.setSpan(
buttonSpan1,
str.indexOf("button1"),
str.indexOf("button1") + String.valueOf("button1").length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spanString.setSpan(
buttonSpan2,
str.indexOf("button2"),
str.indexOf("button2") + String.valueOf("button2").length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

set onclick on multiple links in single textview

I have a string in database that is like:
string f = "this is the first link and this is the second link"
textview1.TextFormatted = Html.FromHtml(f);
url =?
Intent i = new Intent(Android.Content.Intent.ActionView,url);
StartActivity(i);
the number of links in the string is different. I want to make all link in textview clickable and when user click on each of them, the url of that link send to another activity.
When you setText using Html.fromHtml, the '' are replaced as UrlSpans in textView.
You can get each of url spans and set clickable spans for onClick function.
Refer to this for the solution code.
I have achieved the same using SpannableStringBuilder.
Simply initialize the TextView that you want to add 2 or more listeners and then pass that to the following method that I have created:
private void customTextView(TextView view) {
SpannableStringBuilder spanTxt = new SpannableStringBuilder(
getString(R.string.read_and_accept));
spanTxt.setSpan(new ForegroundColorSpan(ContextCompat.getColor(activity, R.color.black_30)), 0,
getString(R.string.read_and_accept).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanTxt.append(" ");
spanTxt.append(getString(R.string.t_and_c));
spanTxt.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
Utils.redirectUserToUrl(activity,"http://luxit-driver-terms.tookan.in");
}
}, spanTxt.length() - getString(R.string.t_and_c).length(), spanTxt.length(), 0);
spanTxt.append(" and ");
spanTxt.setSpan(new ForegroundColorSpan(ContextCompat.getColor(activity, R.color.accent)), 48, spanTxt.length(), 0);
spanTxt.append(getString(R.string.privacy_policy));
spanTxt.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
Utils.redirectUserToUrl(activity,"http://luxit-driver-privacypolicy.tookan.in/");
}
}, spanTxt.length() - getString(R.string.privacy_policy).length(), spanTxt.length(), 0);
view.setMovementMethod(LinkMovementMethod.getInstance());
view.setText(spanTxt, TextView.BufferType.SPANNABLE);
}
In Xml,use android:textColorLink to add custom color for ur link text
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"
android:textColorLink="#000000" />

How to register OnClickListner on hyperlink

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.

Setting clickable string - Textview (Android)

My code looks like this,
String content = "Hi this is #Naveen. I'll meet #Peter in the evening.. Would you like to join #Sam??";
TextView contentTextView=(TextView)userHeader.findViewById(R.id.contentTextView);
contentTextView.setText(content);
Before setting the text in the textview, I would like to add click event for #Naveen, #Peter and #Sam.. When the user taps on these texts I want to open a new intent.. Is that possible? Any pointers would be quite helpful.
You can try to use Linkify with custom patterns.
However, if that doesn't suit your needs you can try this:
SpannableString ss = new SpannableString("Hi this is #Naveen. I'll meet #Peter in the evening.. Would you like to join #Sam??");
ClickableSpan clickableSpanNaveen = new ClickableSpan() {
#Override
public void onClick(View textView) {
//Do Stuff for naveen
}
};
ClickableSpan clickableSpanPeter = new ClickableSpan() {
#Override
public void onClick(View textView) {
//Do Stuff for peter
}
};
ClickableSpan clickableSpanSam = new ClickableSpan() {
#Override
public void onClick(View textView) {
//Do Stuff for sam
}
};
ss.setSpan(clickableSpanNaveen, 11, 17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(clickableSpanPeter, 29, 35, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(clickableSpanSam, 76, 79, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView contentTextView=(TextView)userHeader.findViewById(R.id.contentTextView);
contentTextView.setText(ss);
contentTextView.setMovementMethod(LinkMovementMethod.getInstance());
You can use the Linkify class, which provides methods for adding links to TextViews. You can use the addLinks(TextView textView, Pattern pattern, String scheme) method, which needs you to specify the TextView, a Pattern for the text you want to match and a custom scheme that will be used to match Activities that can work with this kind of data. The Activity that you want to be opened when clicking on links must declare this scheme in its intent-filter. Hope this helps.

Format TextView to look like link

I've been using the android:autoLink just fine for formatting links and such, but I need to use android:onClick so I can't use that in this case. The reasoning is that I find it too easy to click on a phone number accidentally, so I'm going to intercept the click with a confirmation Dialog and then call.
Is there an easy way to still make the phone number in my TextView look like a normal clickable link? I poked around the Android source code, but couldn't find any particular style for me to reference.
This is the shortest solution:
final CharSequence text = tv.getText();
final SpannableString spannableString = new SpannableString( text );
spannableString.setSpan(new URLSpan(""), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(spannableString, TextView.BufferType.SPANNABLE);
Sadly, the effect of clicking doesn't show up as being clicked on a real url link, but you can overcome it like so:
final CharSequence text = tv.getText();
final SpannableString notClickedString = new SpannableString(text);
notClickedString.setSpan(new URLSpan(""), 0, notClickedString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(notClickedString, TextView.BufferType.SPANNABLE);
final SpannableString clickedString = new SpannableString(notClickedString);
clickedString.setSpan(new BackgroundColorSpan(Color.GRAY), 0, notClickedString.length(),
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tv.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(final View v, final MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
tv.setText(clickedString);
break;
case MotionEvent.ACTION_UP:
tv.setText(notClickedString, TextView.BufferType.SPANNABLE);
v.performClick();
break;
case MotionEvent.ACTION_CANCEL:
tv.setText(notClickedString, TextView.BufferType.SPANNABLE);
break;
}
return true;
}
});
Another solution is to use Html.fromHtml(...) , where the text inside has links tags ("") .
If you wish for another solution, check this post.
You can create a colors.xml resource file, what contains colors. Please take a look at Colors
If you want to underline your text, then please take a look at this post:
Underline
Don't forget to add android:clickable="true" or setClickable(true) to
your TextViews to make them clickable!
Linkify is a great class, it hunts for complex patterns like URLs, phone numbers, etc and turns them into URLSpans. Rather than re-write the existing regular expressions I extended the URLSpan class and created a method to upgrade only the telephone URLSpans to a custom URLSpan with a confirmation dialog.
First my extended URLSpan class, ConfirmSpan:
class ConfirmSpan extends URLSpan {
AlertDialog dialog;
View mView;
public ConfirmSpan(URLSpan span) {
super(span.getURL());
}
#Override
public void onClick(View widget) {
mView = widget;
if(dialog == null) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(widget.getContext());
mBuilder.setMessage("Do you want to call: " + getURL().substring(4) + "?");
mBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
openURL();
}
});
dialog = mBuilder.create();
}
dialog.show();
}
public void openURL() {
super.onClick(mView);
}
}
Next the method to swap out the different span classes:
private void swapSpans(TextView textView) {
Spannable spannable = (Spannable) textView.getText();
URLSpan[] spans = textView.getUrls();
for(URLSpan span : spans) {
if(span.getURL().toString().startsWith("tel:")) {
spannable.setSpan(new ConfirmSpan(span), spannable.getSpanStart(span), spannable.getSpanEnd(span), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.removeSpan(span);
}
}
}
Finally all you need to do is create a TextView with the autoLink attribute:
android:autoLink="phone"
And remember to call the swapSpans() method. Understand that I wrote this for fun, there may be other methods of doing this but I am unaware of them at the moment. Hope this helps!
To underline your TextView's text, you have to do something like:
final TextView text = (TextView) findViewById(R.id.text);
SpannableString string = new SpannableString("This is the uderlined text.");
string.setSpan(new UnderlineSpan(), 0, string.length(), 0);
text.setText(string);
This should work. Let me know about your progress.
With kotlin extension function (if you don't need the click effect as on a real link)
fun TextView.hyperlinkStyle() {
setText(
SpannableString(text).apply {
setSpan(
URLSpan(""),
0,
length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
},
TextView.BufferType.SPANNABLE
)
}
How to use
yourTextView.hyperlinkStyle()
Have a better answer.This is what i did.
final SpannableString ss = new SpannableString("Click here to verify Benificiary");
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
};
ss.setSpan(clickableSpan,0,ss.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.BLUE);
You go anywhere you like when user clicks on the link through onclick method of ClickableSpan
Simply underline it:
val myText = "Text to be underlined"
textView.text = Html.fromHtml("<u>$myText</u>")
or with kotlin extensions:
fun TextView.underline() {
text = Html.fromHtml("<u>${text}</u>")
}
usage:
textView.text = myText
textView.underline()
More ways to style text in android here: https://medium.com/androiddevelopers/spantastic-text-styling-with-spans-17b0c16b4568

Categories

Resources