Android Linkify - Clickable telephone numbers - java

So I am trying to add the functionality that when you click on a phone number it would take you to the Dialer app with the pre-populated number. I have the code below:
mContactDetailsText.setText(phonetextBuilder.toString());
Pattern pattern = Pattern.compile("[0-9]+\\s+[0-9]+");
Linkify.addLinks(mContactDetailsText, pattern, "tel:");
and the Text is currently "T. 0123 4567890"
The current outcome is just having the above string without it being clickable. I have even tried added the following line, but to no luck:
mContactDetailsText.setAutoLinkMask(0);
Anyone got any ideas or can see what I am doing wrong?
Thanks

The autolink mask needs to include a search for phone numbers:
mContactDetailsText.setAutoLinkMask(Linkify.PHONE_NUMBERS);
Then you'll need to set the links to be clickable:
mContactDetailsText.setLinksClickable(true);
You might also need movement method set like so:
mContactDetailsText.setMovementMethod(LinkMovementMethod.getInstance())

You should be able to accomplish what you want with the other answers,
but this will definitely work and will give you more control over the display of the text and what will happen when you click the number.
String text = "T. ";
StringBuilder stringBuilder = new StringBuilder(text);
int phoneSpanStart = stringBuilder.length();
String phoneNumber = "0123 4567890"
stringBuilder.append(phoneNumber);
int phoneSpanEnd = stringBuilder.length();
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + phoneNumber.replace(" ", "")));
startActivity(intent);
}
public void updateDrawState(TextPaint ds) {// override updateDrawState
ds.setUnderlineText(false); // set to false to remove underline
ds.setColor(Color.BLUE);
}
};
SpannableString spannableString = new SpannableString(stringBuilder);
spannableString.setSpan(clickableSpan, phoneSpanStart, phoneSpanEnd,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(spannableString);
myTextView.setMovementMethod(LinkMovementMethod.getInstance());

You need to set an onClickListener() on your TextViews. Then they will respond to clicks.

Related

Android ACTION_SEND with special unicode characters

I am trying to send text using an intent. I thought it was straight-forward:
public Intent getIntent() {
final Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, getText());
return intent;
}
private String getText(){
// the emoji can be one of many. I removed all that for brevity
final int unicode = 0x1F3C5;
final String emoji = String.valueOf(Character.toChars(unicode));
// final String emoji = "\n1F3C5"; //didn't work either
// I also tried using HTML here but I think I have some wires crossed, so I am not ruling that out yet
return textPartOne + " " + emoji + " " + textPartTwo;
}
As you can see, the EXTRA_TEXT has a special character in it (an emoji). When the text sends from device A the emoji appears like I expect in the message. But on device B (the receiver) the text shows some madness (usually in two different messages):
#.£¡ù¿ ¡ ¡ | | < | | | \ < | [ ¡ { ¡ [ ¡
#H£(ù#æ#a#¤¥¡
¡9#ü#Hù#Θ#=#ø¥p
¡6#Ö#Δì¿ ¡ |
It doesn't matter if I send the message from device A to device B or B to A. I get the same results either way, so I believe it isn't an issue with the emoji not being supported.
Now, if I remove all but the emoji code:
Xäx&
If I remove the emoji code altogether it works like a charm.
But the client has gotta have those emojis...
😤
Some other things that may be of note:
I am using this to manage what intents I am presenting to the user. They could pick MMS, email, Twitter, Facebook or whatever really. I need to support all of these
I am getting the special characters from Emojipedia
I am not displaying the emojis anywhere in the app. They will be shown in Text message, Email, or Facebook/Twitter feed.
There is already an iOS variant of this app who is successfully doing this.
I have tried nearly a dozen different ways with no avail.
Is there anyone that may have some insight on how to properly send special characters?
Edit:
As you can see, I am sending the emoji I desire. But the result is far from what I expect. This is a screenshot of an emulator sending a text to itself.
Here are some of the ways I have tried
String attempt1 = "--";
try {
attempt1 = Html.fromHtml(new String("&#x1F3C5".getBytes("UTF-8"))).toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
final int codePoint = 0x26F7;
final String attempt2 = new String(new int[]{codePoint}, 0, 1);
final String attempt3 = new String(Character.toChars(codePoint));
final String attempt4 = "\u26F7";
All result in:
&n
If I add text to these:
final String attempt4 = "COME ON: \u26F7";
I get this:
#Σ£(ù#æ#s##£ Å¡7#X£¿ù¿
Which makes total sense he said sarcastically
You can use intents, which are messages sent between activities. In a intent you can put all sort of data, String, int, etc.
In your case, in activity2, before going to activity1, you will store a String message this way :
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", getText());
startActivity(intent);
In activity1, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Then you can set the text in the TextView:
TextView txtView = (TextView) findViewById(R.id.your_resource_textview);
txtView.setText(message);
Hope this helps !

Placing String from strings.xml in the Toast Message

I'm currently finishing my game app for android, but I have encountered one problem that keeps crashing my app.
I was trying to place the text from strings.xml inside the toast message and my code looks like this:
// THIS IS THE PART THAT DOES NOT WORK:
int stringrank = getResources().getIdentifier("rank"+points, "string", this.getPackageName());
rank = getString(stringrank);
// I want to get different rank String depending on the collected points,
// so it would be rank1, rank2, rank3 and so on - thats why "rank"+points.
// It worked for me in the different parts of the code, but when I want to
// use it in the Toast Message it does not.
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.done_toast, (ViewGroup) findViewById(R.id.done_toast));
TextView text = (TextView) layout.findViewById(R.id.text);
// APP CRASHES when I use "rank" String here, if I place other text it works just fine.
text.setText(rank);
final Toast donetoast = new Toast(getApplicationContext());
donetoast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 35);
donetoast.setDuration(Toast.LENGTH_SHORT);
donetoast.setView(layout);
// Rest of the Toast Message code is below, not important.
(...)
When I place the normal text in the Toast Message (does not matter whether in Java or in the done_toast.xml) it works perfectly, but if I want to call the String from strings.xml the app crashes.
Thank you for your help in advance!
You can't create a Toast object like that. It must be done using Toast.makeText().
Try this
final Toast donetoast=Toast.makeText(getApplicationContext());
donetoast.setDuration(Toast.LENGTH_SHORT);
donetoast.setView(layout);

Android Parse how can I use getObjectId(); when setting a ParseUser object?

I have a user search and a listview to populate with the results. The results have an "Add Friend" button.
This is what I have for the onClick:
OnClickListener addRequest = new OnClickListener() {
#Override
public void onClick(View v) {
userConnection = new UserConnection();
userConnection.setCurrentUser(User.getCurrentUser());
userConnection.setOtherUser(users.get(position).getObjectId()); ////HELP, this is where I need to get the objectId for the user and set it as OtherUser
userConnection.setFriendRequestStatus(appConstants.FRIENDREQUESTSTATUS.PENDING);
userConnection.setCurrentUserSentRequest(true);
Utils.showOKdialog(context, "Press OK to send friend request");
userConnection.saveInBackground();
Log.d(TAG, "You have sent a friend request to " + userConnection.getOtherUser().getLastName() + " " + userConnection.getOtherUser().getFirstName());
}
};
I have a comment on which line I need help with, the problem I am having is .getObjectId returns a String and .setOtheruser calls for a ParseUser. Any ideas on how to get the objectId which is a String on the user that is at the position of the list view clicked?
I also tried this but it came back with a null reference for .getParseUser("objectId")
userConnection.setOtherUser(users.get(position).getParseUser("objectId"));
Well I figured it out, I was making things too complicated as usual. The solution is just
userConnection.setOtherUser(users.get(position));

Android: Open alertdialog from part of string?

I have a CheckBox with a string that says "I have read and understood the terms and conditions". Now I want to make the words "terms and conditions" to a link which opens a alertdialog where the terms and conditions can be read. Nothing special.
I'm thinking something in the line of:
<string name="cont_agree">I have read and understood the <a ref="open alertdialog">terms and conditions.</a></string>
Is it possible, and what should I use where it now says "open alertdialog"?
If it can't be done this way, how should I do?
Addition:
To open a url you would use this code:
<string name="cont_agree"><a ref="http://www.stackoverflow.com">Stackoverflow</a></string>
But how do you open a alertdialog, or say another screen, from a string? I have seen apps who does this so it is possible, of course, but how?
EDIT:
This is the code I use for the SpannableStringBuilder:
SpannableStringBuilder text = new SpannableStringBuilder();
text.append(getString(R.string.before));
//Now create a ClickableSpan
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View view) {
d.show(); //Here dialog will be displayed
}
};
//Now append the TOS string
text.append(getString(R.string.popup));
//Declare that the "TOS" string is a clickableSpan
text.setSpan(clickableSpan, getString(R.string.before).length(),getString(R.string.before).length()+getString(R.string.popup).length(), 0); //Check on API setSpan method
((CheckBox)findViewById(yourview)).setMovementMethod(LinkMovementMethod.getInstance());
((CheckBox)findViewById(yourview)).setText(text, BufferType.SPANNABLE);
I still get some markers at the first "text.append" line.
Multiple markers at this line:
Return type for the method is missing
Syntax error on token ")", { expected after this token
R.string.before cannot be resolved to a type
Syntax error on token ")", invalid VariableDeclaratorId
Syntax error on token "append", Identifier expected after this token
First setup your dialog
Dialog d = new Dialog(context);
d.setTitle... etcetc
In your values.xml create 2 string
<string name="before">I have read and understood the</string>
<string name="popup">TOS</string</string>
Now you can use SpannableStringBuilder
SpannableStringBuilder text = new SpannableStringBuilder();
text.append(getString(R.string.before));
//Now create a ClickableSpan
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View view) {
d.show(); //Here dialog will be displayed
}
};
//Now append the TOS string
text.append(getString(R.string.popup));
//Declare that the "TOS" string is a clickableSpan
text.setSpan(clickableSpan, getString(R.string.before).length(), getString(R.string.before).length()+getString(R.string.popup).length(), 0); //Check on API setSpan method
((CheckBox)findViewById(yourview)).setMovementMethod(LinkMovementMethod.getInstance());
((CheckBox)findViewById(yourview)).setText(text, BufferType.SPANNABLE); //AAAAND WE'RE DONE!

Append formatted text to a EditText View

I have an EditText view which I am using to display information to the user. I am able to append a String and it works correctly with the following method:
public void PrintToUser(String text){
MAIN_DISPLAY.append("\n"+text);
}
The application is an RPG game which has battles, when the user is fighting I would like to display the String in RED. So I have attempted to use a SpannableString. (changed the method)
public void PrintToUser(String text, int Colour){
if(Colour == 0){
//Normal(Black) Text is appended
MAIN_DISPLAY.append("\n"+text);
}else{
//Colour text needs to be set.
//Take the CurrentText
String CurrentText = MAIN_DISPLAY.getText().toString();
CurrentText = CurrentText+"\n";
SpannableString SpannableText = new SpannableString(CurrentText + text);
switch(Colour){
case 1:
SpannableText.setSpan(new ForegroundColorSpan(Color.RED), CurrentText.length(), SpannableText.length(), 0);
break;
}
//You cannot append the Spannable text (if you do you lose the colour)
MAIN_DISPLAY.setText(SpannableText, BufferType.SPANNABLE);
}
This new method works and the new line is displayed is red.
Problems
Only the last line formatted is red. If a new line is set to be red the previous formatting is lost due to the way I retrieve the text
String CurrentText = MAIN_DISPLAY.getText().toString();
When I was ONLY appending Strings to the EditText it was displaying the bottom of the EditText box (the last input) now when using SetText the users see's the Top.
Finally My Question:
Is there a way to Append the formatted text?
OR... Can I retrieve the formatted text from the EditText and then when I use .setText I can keep the current format?
AND if so... Is there a way to focus the Display at the Bottom opposed to the Top?
Thank you! Please comment if additional information is needed I've been stuck on this for a while now.
My suggestion would be to use the method:
myTextView.setText(Hmtl.fromHtml(myString));
Where the myString could be of the format:
String myString = "Hello <font color=\'#ff0000\'>World</font>";
The following modifications to PrintToUser() should work..
public void PrintToUser(String text, int Colour){
...
...
Editable CurrentText = MAIN_DISPLAY.getText();
int oldLength = CurrentText.length();
CurrentText.append("\n" + text);
switch(Colour){
case 1:
CurrentText.setSpan(new ForegroundColorSpan(Color.RED),
oldLength, CurrentText.length(), 0);
break;
}
}
Try to change
SpannableText.setSpan(new ForegroundColorSpan(Color.RED), CurrentText.length(), SpannableText.length(), 0);
on
SpannableText.setSpan(new ForegroundColorSpan(Color.RED), 0, SpannableText.length(), 0);

Categories

Resources