the_prole
the_prole

Reputation: 8945

How to convert a String array to a CharSequence?

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

Upvotes: 2

Views: 16327

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

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.

Upvotes: 10

Related Questions