Saturday, May 23, 2015

How to strikethrough TextView text programmatically in Android

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="24dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Apply Text Strike Through"
        android:textAllCaps="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:textSize="24sp"
        android:fontFamily="monospace"
        android:text="Lorem ipsum dolor sit amet, consectetur
         adipiscing elit. Proin aliquet magna vel lorem tempus
         pharetra. Praesent ut erat non mi semper porta.
         Pellentesque in dui aliquam, scelerisque diam at,
         dignissim magna."
        android:padding="32dp"
        android:background="#FEFEFA"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/button"/>

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java

package com.cfsuman.androidtutorials;

import android.graphics.Paint;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        Button button = findViewById(R.id.button);
        TextView textView = findViewById(R.id.textView);

        // Button click listener
        button.setOnClickListener(view -> {
            // Set TextView text strike through
            textView.setPaintFlags(
                    textView.getPaintFlags()|
                            Paint.STRIKE_THRU_TEXT_FLAG
            );
        });
    }
}