I wrote code that set/unset bold and italic style to textview. And it works perfect, but my Android Studio have a little trouble with it.
style &= (int) ~Typeface.BOLD; - Android Studio tells me, that casting to (int) is redundant, but when I delete it, then it shows that flag is not allowed there. This has no impact on the operation of the program - it works anyway.
So the questions are:
Why Android Studio tells me that casting is redundant, but when I delete it then tells that flag isn't allowed here?
Is my code a correct way of changing italic/bold style in textview?
Fragment of my class:
Textview textview = findViewById(R.id.tv1)
CheckBox bold = findViewById(R.id.checkBoxBold);
bold.setOnCheckedChangeListener((buttonView, isChecked) -> {
Typeface typeface = textview.getTypeface();
int style = typeface.getStyle();
if (isChecked) style |= Typeface.BOLD;
else style &= (int) ~Typeface.BOLD;
Typeface newTypeface = Typeface.create(textview.getTypeface(), style);
textview.setTypeface(newTypeface);
});
CheckBox cursive = findViewById(R.id.checkBoxCursive);
cursive.setOnCheckedChangeListener((buttonView, isChecked) -> {
Typeface typeface = textview.getTypeface();
int style = typeface.getStyle();
if (isChecked) style |= Typeface.ITALIC;
else style &= (int) ~Typeface.ITALIC;
Typeface newTypeface = Typeface.create(textview.getTypeface(), style);
textview.setTypeface(newTypeface);
});
I've seen people make just if statements for all cases, but I'm not sure about that method.
So you are having problems with setting typeface to your edittext/textview programmatically.
To your first question - TypeFace.Bold or TypeFace.Italic returns an Integer whereas edittext or textview needs Typeface.
Second the correct or the easiest way to set typeface to a view is as follows :
You can do the same for all typefaces. I hope this helps you. Do let me know if this doesn't help. I would be happy to help.