Android: Statically underline dynamic text in TextView - android

I would like to make a TextView to be entirely underlined but I can't use a text resource and <u> tag because it is dynamic text.
Related: Can I underline text in an android layout?
So far the only way I know to do this is at runtime. Is this really the only way? Is there a way I could do it in the XML files?

The easiest solution is probably to create a custom UnderLineTextView component deriving from TextView, override setText() and set the entire text as underlined, something like this (underline code from the link you referred to above):
#Override
public void setText(CharSequence text, BufferType type) {
// code to check text for null omitted
SpannableString content = new SpannableString(text);
content.setSpan(new UnderlineSpan(), 0, text.length(), 0);
super.setText(content, BufferType.SPANNABLE);
}
It's then just a matter of using your new component in the layout and setting the text as usual. The rest is handled automatically.
More info on custom components:
http://developer.android.com/guide/topics/ui/custom-components.html

You can underline text over Html.fromHtml(String source)
Example:
textView.setText(Html.fromHtml("this is <u>underlined</u> text"));

You can also do this via the /res/values/string.xml file if you prefer: For example, in the /res/values/string.xml you could add an entry like:
<string name="createAccount"><u>Create Account</u></string>
And then in the onCreate(Bundle savedInstanceState) method of your activity you would add the following code to cause "Create Account"> to appear as underlined in the UI that you set for the createAccountText TextView that you defined in the xml file in /res/layout/ for your activity:
TextView createAccountText = (TextView) findViewById(R.id.createAccountText);
Resources res = getResources();
CharSequence styledText = res.getText(R.string.createAccount);
createAccountText.setText(styledText, TextView.BufferType.SPANNABLE);

peter3 wrote before to extend TextView class and override setText method.
This solution won't work as setText method is marked as FINAL.
http://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)
Not sure if the code could work with some modifications.

SpannableString content = new SpannableString(name);
content.setSpan(new UnderlineSpan(), 0, name.length(), 0);
geometrical_textview.setText(content, TextView.BufferType.SPANNABLE);

Related

How to add drawable image inside textview

I need a drawable within the text, just like an emoji, so e.g.
"Please press the button looking like this 👥 and then proceed ..."
but with a custom drawable instead of the emoji in my example. (How) is this possible?
I need a drawable within the text
You can Use ImageSpan
Span that replaces the text it's attached to with a Drawable that can be aligned with the bottom or with the baseline of the surrounding text. The drawable can be constructed from varied sources:
but with a custom drawable instead of the emoji in my example. (How) is this possible?
Try this working example
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView=findViewById(R.id.tv);
Spannable span = new SpannableString("Please press the button looking like this and then proceed ..");
Drawable test = getResources().getDrawable(R.drawable.abc);
test.setBounds(0, 0, 32,32);
ImageSpan imageSpan = new ImageSpan(test, ImageSpan.ALIGN_BASELINE);
span.setSpan(imageSpan, 36, 37, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(span);
}
}
RESULT
You can try unicode:
int unicode = 0x1F60A;
And use it like this:
public String getEmojiByUnicode(int unicode){
return new String(Character.toChars(unicode));
}

How to change a strings color?

I want to change this string to the color red
String isFalse = False;
For some reason every tutorial seemed more complicated than I expected and I don't understand them. Is there a simple way to do this? Also, would this override the color of a textview? Because I would like it to.
String is not View, so it has no color at all.
Maybe what you want is to change the appearance color of it host TextView. To achieve this you can use:
TextView text;
//the initialize of this TextView
text.setText(isFalse);
text.setTextColor(Color.Red);
The parameter of the color could be resource from your color XML values file or android.R.color resource file, or from Color class, etc.
Please use this code.
SpannableStringBuilder builder = new SpannableStringBuilder();
String isFalse = "False";
SpannableString redSpannable= new SpannableString(isFalse);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, Tru_score.length(), 0);
builder.append(redSpannable);
TextView text1 = (TextView)findViewById(R.id.textView1);
text1.setText(builder, BufferType.SPANNABLE);
It is not complicated or hard
Addressing both possibilities..
You want to change the color for your text at runtime.
that would be like TextView.setTextColor()
i.e.
falseTextView.setTextColor(getResources().getColor(R.color.red))
if you wanted a segment of the same textview to have a different color,by which I mean that the isFalse string is only apart of the content of your TextView ,you need to use as mentioned in the other answer.
Try this...
string.xml
<string name="isFalse"><![CDATA[<b><font color=#FF0000>False</b>]]></string>
MainActivity.java
TextView textView1 = (TextView)findViewById(
R.id.textView1);
textView1.setText(Html.fromHtml(isFalse));
And result, you might get like this...

Android: add "internal" links to part of a TextView, that links to action in my code

As the title explains, I'd like to add links to my TextView, with these two caveats:
I want the link to act on a part of the TextView, not the full one (something like an A anchor in HTML).
I want the link to point to an action in my code, not a website. I could define a method in my activity, or implement an OnClickListener, and execute that when that specific link is clicked.
So far, I succeeded to turn phone numbers, addresses, web sites and emails into dedicated external links using:
Linkify.addLinks(message, Linkify.ALL);
I'd like something similar for internal links (to my method), with the possibility to define custom ones.
Also, using a web page with internal link and a web view is not really an option, as I already have several complex layouts defined, and having to modify the whole application and concepts would be quite a pain...
Any idea?
EDIT: Kabuko gave me a very good solution, here is exactly how I implemented it:
final TextView descriptionTextView = (TextView) findViewById(R.id.description);
final Spannable span = Spannable.Factory.getInstance().newSpannable("the full text for the view");
span.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(StartEventActivity.this, "LINK CLICKED", Toast.LENGTH_SHORT).show();
}
}, 1, 20, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // 1 and 20 to be replaced with actual index of start and end of the desired link
descriptionTextView.setText(span);
descriptionTextView.setMovementMethod(LinkMovementMethod.getInstance());
If you wanted to actually go to URLs you could use Html.fromHtml, but if you want your own click handlers you can use a ClickableSpan.
In completion of previous post this might help some one
TextView textView = (TextView) getView().findViewById(R.id.textView);
textView.setText(Html.fromHtml(getString(R.string.html_)) , TextView.BufferType.SPANNABLE);
String tmp = ((Spannable) textView.getText()).toString();
String linkText = getString(R.string.html_link);
int index = tmp.indexOf(linkText);
if(index>=0) {
Spannable spannable = (Spannable) textView.getText() ;
spannable.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
try {
/// do what you must
}catch (Exception ex){
handleException(ex);
}
}
}, index, index+getString(R.string.html_link).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannable);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}

Formatted text in TextSwitcher?

I'm using a TextSwitcher, however the setText() method takes in a CharSequence rather than an resID integer. If I use getString(resID) the formatting is stripped out. Is there a way to get formatted text (with bold and italics) to show in a TextSwitcher?
Learn about SpannableStringBuilder, this is so useful in producing styled text.
Then just create your formatted strings like:
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append("Hi, abc!");
sb.setSpan(new ForegroundSpan(0xffff0000), 4, 7, 0); // set characters 4 to 7 to red
yourTextWidget.setText(sb, BufferType.SPANNABLE);
Edit: TextSwitcher is just a small wrapper to ViewSwitcher. Examining the sources of TextSwitcher reveals:
/**
* Sets the text of the next view and switches to the next view. This can
* be used to animate the old text out and animate the next text in.
*
* #param text the new text to display
*/
public void setText(CharSequence text) {
final TextView t = (TextView) getNextView();
t.setText(text);
showNext();
}
So, just call this instead of setText:
final TextView t = (TextView) yourWidget.getNextView();
t.setText(sb, BufferType.SPANNABLE);
yourWidget.showNext();
In order to set a formatted text to a TextView, you need to use Html.fromHtml(String). Keep in mind, Spannedimplements from CharSequence.
You can also use Resources.getText(int) to get a styled CharSequence from your application resources.

TextView: how to dynamically change the color of certain word in paragraph

How to change the color of a paragraph word by word with timer. like at first second i want to change color of The in the below paragraph, after 5th second change color of text, after 8th second change color of will be and so on....
The text will be wrapped in tags, and displayed in a monospaced font.
just use Timer and change the font color of your edit text accordingly and stop timer in focus lost.
i think you can do something like this :
Split the paragraph to words by using the method :
split(String separator);// it will return an array of Strings
//in your case you will do somthing like this
myWords = paragraph.split(" ");// the separator is the space
And then , you can use the method to colorate what ever you want of those words by using the method :
myNewParagraph.append(HTML.fromHtml("<font color...>... Your HTML Code to colorate your Text"));
and when you finish coloring each word , you update your textView to display the new text colored
Hope it helps
You can use spans to control the appearance of text. Take a look at Spannable and CharacterStyle.
Here is an example. Of course you would need to put this in some sort of timer.
Spannable spannableText = getSpannableText(yourTextView);
spannableText.setSpan(new TextAppearanceSpan(...), wordStart, wordEnd)
yourTextView.setText(spannableText);
private Spannable getSpannableText(TextView tv) {
CharSequence cs = tv.getText();
if (cs instanceof Spannable) {
return (Spannable)cs;
} else {
return SpannableString.valueOf(cs);
}
}

Categories

Resources