0

I'm trying to set the text of a button from an array using a AlertDialog. I can bring up the array within the AlertDialog with no problem but how do I set the text to the item chosen? Any help would be appreciated, thanks.

Here's my array

<string-array name="Months">
    <item>January</item>
    <item>February</item> <item>March</item> <item>April</item>
    <item>May</item> <item>June</item> <item>July</item>
    <item>August</item> <item>September</item> <item>October</item>
    <item>November</item> <item>December</item>
</string-array>

And here is where I want to set the text

    button.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Select a month");
            builder.setItems(R.array.Months, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                button.settext(""); // how do i set the text of the chosen item
                }
            });
            builder.create().show();
            return false;
        }
    });

2 Answers 2

1

try this: getResources().getStringArray(R.array.Months)[which];

Sign up to request clarification or add additional context in comments.

Comments

0

I would recommend doing it like this:

String[] months = { "January", "February", "March", ... "December" };

button.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Select a month");
        builder.setItems(months, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                button.setText(months[which]);
            }
        });
        builder.create().show();
        return true;
    }
});

Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.