If you ever need to do this in Android, here is how you do it, or at least a relatively simple way I found to do it. If you just search the Android documentation, you will find this reference page. As you can see for static text, it really is quite simple. It is very similar to doing it in HTML.
<resource> <string id="@+id/strike_one"><strike>Strike one!</strike></string> </resources>Nice! Android rocks! But what if your text is dynamic? Well if you keep reading the documentation referenced above, you get into the world of Spannable. This sounds good at first, because it sounds like it's again inspired from HTML. If you look at the sample, it is not so simple. Still, it's not too hard, maybe just a little awkward. But wait, there's more. The class most commonly used for text, TextView, is not a Spannable. Instead, you must use an EditText, which is a subclass of TextView. This is a class that you would not normally use for normal text on the screen, instead you would use it for a text input field.
Turns out there is an easy way to strikethrough a TextView after all. Well easy, if you don't mind use some bit twiddling:
TextView someLabel = (TextView) findViewById(R.id.some_label); someLabel.setText(someDynamicString); someLabel.setPaintFlags(someLabel.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);What is going on here? For painting text, there are several bit flags for doing things like bold, italics, and yes strikethrough. So to enable the strikethrough, you need to flip the bit that corresponds to this flag. The easiest way to do this is to use a bitwise-or on the current flags and a constant that corresponds to a set of flags with only the strikethrough flag enabled. For any other bit flags that are already set, this will have no effect. Actually if the strikethrough flag happened to be already set, this will have no effect. However, if it is not set, then it will flip it, so that it will be set and thus add a nice strikethrough effect.
This is genius. The Spannable thing must be one of the most annoying parts of Android. Thanks for this tip!
ReplyDeleteThanks for sharing. Really helpful!
ReplyDeleteGood one..thanks..
ReplyDeleteOne year old but still useful, thanks a lot !
ReplyDeleteThank you for sharing this!
ReplyDeleteThanks for creating this good information about android, because i got a good knowledge. so you can create more blog with useful information and most of them get benefits from here.
ReplyDeleteThis is one of the forward and good post.I like your blog detail.This si one of teh knowledgeable post.
ReplyDelete