Can we have vertical buttons in an Android alert dialog?

五迷三道 提交于 2020-01-02 04:01:13

问题


By default, we get two or three buttons that are horizontally aligned in an alert dialog. Is it possible to have them vertically aligned within the alert dialog?


回答1:


Sure, you can use Dialog.setContentView() to set the content of a dialog to be an arbitrary layout.

Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.yourLayoutId);
dialog.show();

Make yourself a layout file with a Vertical LinearLayout that has the buttons you want in it and call setContentView() on your dialog, passing the name of your layout file.

If you are deadset on AlertDialog you can do something similar with builder.setView()

LayoutInflater inflater = (LayoutInflater) 
        getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.yourLayoutId,
        (ViewGroup) findViewById(R.id.yourLayoutRoot));
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setView(layout);
AlertDialog alertDialog = builder.create();
alertDialog.show();



回答2:


There has been a setItems() call which does this since API level 1. No reason to create a custom dialog unless you want to change the look and feel of the items.

CharSequence[] items =  {"Foo", "Bar", "FooBar"};
new AlertDialog.Builder(activity)
.setTitle("Choose a widget")
.setItems(items, new DialogInterface.OnClickListener()
{
     @Override
     public void onClick(DialogInterface dialog, int which)
     {
         switch(which)
         {
             case FOO:
             // foo case
             break;

             ....
         }
     }
}
.create().show();


来源:https://stackoverflow.com/questions/9641579/can-we-have-vertical-buttons-in-an-android-alert-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!