Search code examples
androidstrikethrough

Change strike-through in selected text in a textView


I was trying to strike a string in a textView when i select it ,then when i select it a second time it will be unstroken ,this is working for me but the problem is when i select this textView a third time it won't be stroken ,so can any one help me plz , this is my code :

public class MainActivity extends AppCompatActivity {
TextView txt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt = (TextView) findViewById(R.id.txt);

        strike();

}


public void strike() {

    txt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            txt.setPaintFlags(txt.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            //to remove strike
            txt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    txt.setPaintFlags(0);


                }
            });
        }
    });
}

}


Solution

  • Your problem is that youre overriding the onClickListener after first click, so the listener would only clear the paint flags after the first click.

    txt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(txt.getPaintFlags() == 257){
                txt.setPaintFlags(txt.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); 
            } else if(txt.getPaintFlags() == 273){ 
                txt.setPaintFlags(257); 
            }
        }
    });