I'm trying to assign a single char to a TextView in Android Java.
Using a string works:
textView.setText("X");
But using a char aborts at runtime:
textView.setText('X');
and:
char Key5 = 'X';
textView.setText(Key5);
Using a Character also aborts at runtime:
Character Key5 = 'X';
textView.setText(Key5);
Typecasting the Character to a string does work:
Character Key5 = 'X';
textView.setText(Key5.toString());
How do I assign a plain char variable to a TextView?
You can "convert" a character into a String with the method String.valueOf(char):
char key = 'X';
textView.setText(String.valueOf(key));
Short answer:
You can't, you must use a CharSequence. (Thanks Sam)
Long answer:
The problem is that TextView.setText is not overloaded to take a character as the only parameter. It can only take a CharSequence.
From the CharSequence documentation
This interface represents an ordered set of characters and defines the methods to probe them.
String works because it implements the CharSequence inteface. It doesn't make sense to have a CharSequence that only holds one character
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With