Getting default padding for AlertDialog

后端 未结 3 767
灰色年华
灰色年华 2021-02-02 05:40

I need to make a AlertDialog with a custom view. The message of a AlertDialog has a default padding but when i set a view it has no padding, i wand to

3条回答
  •  花落未央
    2021-02-02 06:14

    I got stuck with the same problem, so had to find the answer. In case anyone comes looking for the answer, here is my solution.

    The source code for AlertDialog's layout is described in alert_dialog.xml (e.g. here for android 4.4.1, which should correspond to Holo theme). Layout has hard-coded paddings (and they might be different in different versions of android). To know the default padding you have to sum up all paddings for Views containing id/message" TextView. In this case they are 3+14+5=22 dp left and 1+10+5=16 dp right.

    The android:id/custom element is where a custom view gets inserted into and it has 3 dp left and 1 dp right paddings (from the root element, others do not have paddings) which you do not have to set manually.

    So to have resulting padding of a custom View be the same as message's, set it to 19 dp left and 15 dp right (and don't forget to keep default 5 dp top and bottom padding).

    Example code:

    final EditText input = new EditText( getContext() );
    float dpi = ctx.getResources().getDisplayMetrics().density;
    AlertDialog dialog = (new AlertDialog.Builder(getContext()))
            .setTitle("Rename track")
            .setMessage("Track name:")
            .setPositiveButton("OK", null)
            .setNegativeButton("Cancel", null)
            .create();
    dialog.setView(input, (int)(19*dpi), (int)(5*dpi), (int)(14*dpi), (int)(5*dpi) );
    dialog.show();
    

    These code gives result like this (looks good). BTW, this is Material theme, which seems to have the same paddings (also hardcoded).

    []

提交回复
热议问题