我需要使用自定义视图制作AlertDialog
。
AlertDialog
的消息有一个默认填充,但是当我设置一个视图时它没有填充,我想要获得与默认消息相同的填充。我使用了扩展Holo主题的风格(如果这是相关的)。
AlertDialog.Builder builder = new AlertDialog.Builder(PlaylistListView.this.getContext());
builder.setTitle("Title");
builder.setView(inflate(context, R.layout.music_player_create_dialog, null));
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();
这是内容的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/abc_dialog_padding_material"
android:paddingRight="@dimen/abc_dialog_padding_material"
android:paddingTop="@dimen/abc_dialog_padding_top_material"
android:paddingBottom="@dimen/abc_dialog_padding_top_material">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:background="@null"
android:layout_marginTop="20dp"/>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="@color/divider"/>
</LinearLayout>
答案 0 :(得分:69)
?dialogPreferredPadding
属性现在具有此值。它是在API 22中引入的;见https://developer.android.com/sdk/api_diff/22/changes/android.R.attr.html。
通过在对话框的布局中指定此属性,可以在自定义对话框中获得一致的填充。例如,android:paddingLeft="?dialogPreferredPadding"
会使对话框的内容与其标题保持一致。
答案 1 :(得分:20)
我遇到了同样的问题,所以不得不找到答案。如果有人来寻找答案,这是我的解决方案。
Alertdialog的布局源代码在alert_dialog.xml中描述(例如here for android 4.4.1,它应该与Holo主题相对应)。布局有硬编码填充(在不同版本的android中它们可能有所不同)。要知道默认填充,您必须总结包含id/message"
TextView的视图的所有填充。在这种情况下,它们是3 + 14 + 5 = 22 dp左和1 + 10 + 5 = 16 dp右。
android:id/custom
元素是自定义视图插入的位置,它有3 dp左和1 dp右边距(来自根元素,其他没有填充),您不必手动设置。
因此,要使自定义视图的结果填充与消息相同,请将其设置为左侧19 dp和右侧15 dp(并且不要忘记保持默认的5 dp顶部和底部填充)。
示例代码:
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();
这些代码给出了这样的结果(看起来不错)。顺便说一句,这是Material主题,它似乎有相同的填充(也是硬编码)。
[]
答案 2 :(得分:0)
只需添加有关如何使用它的更完整答案:
您可以在布局XML文件android:paddingStart="?dialogPreferredPadding"
和android:paddingEnd="?dialogPreferredPadding"
中使用。
或者,如果您想通过代码来实现:
@JvmStatic
fun getDimensionFromAttribute(context: Context, attr: Int): Int {
val typedValue = TypedValue()
return if (context.theme.resolveAttribute(attr, typedValue, true)) TypedValue.complexToDimensionPixelSize(typedValue.data, context.resources.displayMetrics) else 0
}
用法:
val alertDialogPadding = getDimensionFromAttribute(context, R.attr.dialogPreferredPadding)
view.setPadding(alertDialogPadding, 0, alertDialogPadding, 0)
如果您使用CheckBox(可能还有其他一些视图),则我认为不可能设置填充或边距,以使其与对话框中的其他视图很好地对齐,除非您用其他包装查看或扩展