Strikethrough Text in Android
In this article, we are going to implement the strike-through feature on our TextView using this method. This can be useful when we want to edit our content but also want users to see the previous content. Like on the Amazon app we all have seen that the prices are shown with strikethrough when there is a discount on the item and the current price is shown side by side. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Create a drawable file with the name strikethrough and will be adding this drawable file in the text file
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="false"> <shape android:shape="line"> <stroke android:width="1dp" android:color="@android:color/black"/> </shape> </item> </selector>
Create a string like this and will be adding this string as text in TextView
<string name="strike"> Geeks <strike>For Geeks </strike> </string>
Input the following line in the MainActivity.java file.
strike.setPaintFlags(strike.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Implementation of Three Methods
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
Step 3: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.