Remove a Paint Flag in Android

2019-01-21 08:24发布

问题:

My code looks like this:

    TextView task_text = (TextView) view.findViewById(R.id.task_text);
    task_text.setPaintFlags( task_text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

This causes a strike through effect to appear on the text. However, I'd like to know how to remove the flag once set, and how to detect that the flag is set.

I understand this is a bitwise operation, but I've tried both ~ and - operators, neither work.

回答1:

To remove a flag, this should work:

task_text.setPaintFlags( task_text.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));

Which means set all the set flags, except of Paint.STRIKE_THRU_TEXT_FLAG.

To check if a flag is set (Edit: for a moment I forgot it is java...):

if ((task_text.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG) > 0)


回答2:

This also works:

task_text.setPaintFlags(0);


回答3:

Use exclusive OR operator ^ instead of | with &(~) combination:

// setup STRIKE_THRU_TEXT_FLAG flag if current flags not contains it
task_text.setPaintFlags(task_text.getPaintFlags() ^ Paint.STRIKE_THRU_TEXT_FLAG));

// second call will remove STRIKE_THRU_TEXT_FLAG
task_text.setPaintFlags(task_text.getPaintFlags() ^ Paint.STRIKE_THRU_TEXT_FLAG));

Check if flag is currently setup:

if((task_text.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG) == Paint.STRIKE_THRU_TEXT_FLAG)


回答4:

|--------------------------------------------------|
|<*>| Underline with a textView :
|--------------------------------------------------|

|*| Add Underline :

 txtVyuVar.setPaintFlags(txtVyuVar.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

|*| Remove Underline :

txtVyuVar.setPaintFlags(txtVyuVar.getPaintFlags() ^ Paint.UNDERLINE_TEXT_FLAG);

|*| Check Underline :

if((txtVyuVar.getPaintFlags() & Paint.UNDERLINE_TEXT_FLAG) == Paint.UNDERLINE_TEXT_FLAG)
{
    // Codo Todo
}

|*| Toggle Underline :

if((txtVyuVar.getPaintFlags() & Paint.UNDERLINE_TEXT_FLAG) == Paint.UNDERLINE_TEXT_FLAG)
{
    txtVyuVar.setPaintFlags(txtVyuVar.getPaintFlags() ^ Paint.UNDERLINE_TEXT_FLAG);
}
else
{
    txtVyuVar.setPaintFlags(txtVyuVar.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
}


回答5:

In my opinion, just set its default flag is a better choice. Otherwise, the text will be looked jagged. The default flag in TextView (EditText extends TextView) is

Paint.ANTI_ALIAS_FLAG

And set a new paintflag will replace the previous one. I have made a test to verify it. So, just like this:

task_text.setPaintFlags(Paint.ANTI_ALIAS_FLAG);


回答6:

In Kotlin

task_text.paintFlags = task_text.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()