Android: Open alertdialog from part of string? - java

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!

Related

Get selected text in webview to highlight it in java

I'd like to allow users to highlight in yellow text in my webview.
So I wanna use some javascript to allow my app to get the selected text:
mWebview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
#Override
public void onReceiveValue(String value)
{
Log.v(TAG, "Webview selected text: " + value);
}
});
Ok, this will get the selected text in the webview. Now I need to save this texts in sharedpreferences to remember it next time user open the app, then find all the texts saved to highlight. Any ideas how to do this?

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 Linkify - Clickable telephone numbers

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.

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);

split method for text value in Appcelerator

I have a window that displays my tweets in a label.
My tweets come from my FB page statuses and if i have put a pic or write more than 140 characters then i get a link in tweet to the actuall post.
I wonder if there is any way to get the label text to split so i can point the link into an url to open in webview
This is how far i have got:
var win = Ti.UI.currentWindow;
win.showNavBar();
var desc = Ti.UI.createLabel({
text: win.data,
font:{
fontSize:'20dp',
fontWeight:'bold'
},
height:'300dp',
left:'5dp',
top:'10dp',
color:'#111',
touchEnabled:true
});
win.add(desc);
desc.addEventListener('click',function(e){
var v = desc.text;
if(v.indexOf('http') != -1){
// open new window with webview
var tubeWindow = Ti.UI.createWindow({
modal: true,
barColor: '#050505',
backgroundColor: '#050505'
});
var linkview = Ti.UI.createWebView({
url: e.v,
barColor: '#050505',
backgroundColor: '#050505'
});
// Create a button to close the modal window
var close_modal = Titanium.UI.createButton({title:'Stäng'});
tubeWindow.rightNavButton = close_modal;
// Handle close_modal event
close_modal.addEventListener('click', function() {
tubeWindow.close();
});
tubeWindow.add(linkview);
tubeWindow.open({
modalTransitionStyle: Ti.UI.iPhone.MODAL_TRANSITION_STYLE_FLIP_HORIZONTAL,
});
}
});
win.open();
What i´ve been told i need to split the win.data to get the link. (win.data is the tweet)
now i just have: url: e.v, i need to get the link out
Any ideas on how this can work?
Thanx
//R
I did a similar thing a while ago. pull down the tweet(s) run the text through a regular expression to pull out a URL.
What I did was put each tweet in a tableview row, and set the tableview row to hasChild=true if the regular expression returned anything, then onClick of a tableView row, if hasChild == true open a webview with the given URL (stored in the row).
A regualr expression like the one here should work:
http://www.geekzilla.co.uk/view2D3B0109-C1B2-4B4E-BFFD-E8088CBC85FD.htm
So something like:
str= <<tweet text>>;
re= <<URL expression>>;
check=str.match(re);
now check contains either null or a url.

Categories

Resources