Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String array to a CharSequence?

Tags:

java

android

I need to display a dialogue with a list of colors to choose from. I found this solution here.

CharSequence colors[] = new CharSequence[] {"red", "green", "blue", "black"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(colors, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // the user clicked on colors[which]
    }
});
builder.show();

I already have a String array of colors. How can I convert it to a CharSequence? I was thinking to use type casting

CharSequence colors[] = (CharSequence) mStringArray;

But this route does not work

like image 213
the_prole Avatar asked Mar 23 '26 15:03

the_prole


1 Answers

A String is already a CharSequence and since arrays are covariant in Java, a String[] is already a CharSequence[]. You probably don't need a cast at all, but if you use one it should be (CharSequence[]) mStringArray.

like image 180
Ted Hopp Avatar answered Mar 26 '26 06:03

Ted Hopp



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!