Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a single char to a TextView

Tags:

java

android

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?

like image 775
Humanoid1000 Avatar asked Oct 17 '25 09:10

Humanoid1000


2 Answers

You can "convert" a character into a String with the method String.valueOf(char):

char key = 'X';
textView.setText(String.valueOf(key));
like image 181
Stephan Markwalder Avatar answered Oct 18 '25 23:10

Stephan Markwalder


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

like image 27
Robert Estivill Avatar answered Oct 18 '25 22:10

Robert Estivill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!