Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AlertDialog Set Items to align centre

How do I align the items in an AlertDialog to centre created by dialog.setItems()?

For example, this creates a dialog with options for several times with default left alignment:

AlertDialog.Builder timeOutDialog = new AlertDialog.Builder(getActivity());
timeOutDialog.setTitle("Set Timer");
final String[] types = {"5 min", "15 min", "30 min", "1 hour", "3 hours", "6 hours", "12 hours", "24 hours"};

timeOutDialog.setItems(types, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
        switch(which){
            case 0: // 5m
                timerLength = 0;
                break;

            case 1: // 15m
                timerLength = 1;
                break;

            // ...
        }
        timeOutButton.setText(types[which]);
    }

});

AlertDialog dialog = timeOutDialog.show();

I know that there are ID's to set alignment for title and message. are there ID's that allow setting the alignment as does with title and message (ex. android.R.id.message)?

I searched for answers and many said the only way to do this is to inflate the dialog or create a custom dialog xml with a custom centred spinner. Are those my only options?

like image 929
William Yang Avatar asked Sep 19 '25 23:09

William Yang


1 Answers

Thanks for everyone's interest,

I have found the solution through using a library called material-dialogs

With it I am able to centre the title as well as the spinner. In my experience centring a popup spinner using vanilla android was very time consuming thus far.

@OnClick(R.id.list)
    public void showList() {
        new MaterialDialog.Builder(this)
                .title(R.string.socialNetworks)
                .items(R.array.socialNetworks)
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                        showToast(which + ": " + text);
                    }
                }).itemsGravity(GravityEnum.CENTER)
                .titleGravity(GravityEnum.CENTER)
                .show();
    }
like image 91
William Yang Avatar answered Sep 22 '25 13:09

William Yang