Humanoid1000
Humanoid1000

Reputation: 175

How to assign a single char to a TextView

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?

Upvotes: 4

Views: 4867

Answers (2)

Robert Estivill
Robert Estivill

Reputation: 12477

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

Upvotes: 2

Stephan Markwalder
Stephan Markwalder

Reputation: 233

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

char key = 'X';
textView.setText(String.valueOf(key));

Upvotes: 10

Related Questions