Android 使对话框宽度与自定义正按钮宽度相同

Android 使对话框宽度与自定义正按钮宽度相同,android,Android,我正在为如下对话框使用自定义布局: public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new Builder(getActivity()); View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_code_dialog, null); builder.setView(

我正在为如下对话框使用自定义布局:

public Dialog onCreateDialog(Bundle savedInstanceState) {

    Builder builder = new Builder(getActivity());
    View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_code_dialog, null);
    builder.setView(dialogView);

    builder.setPositiveButton("", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            listener.onDialogPositiveClick(CodeDialogFragment.this);
        }
    });
    return builder.create();
}
使用此xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context="XXX.fragments.CodeDialogFragment">

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="@string/code_text"
    android:padding="@dimen/medium_body_padding"
    android:id="@+id/code_text"
    />
</RelativeLayout>
我的问题是,我的设计要求对话框的宽度与按钮的宽度相同,但当按钮被覆盖时,将宽度设置为
wrap\u content
不起作用。更换按钮后,如何更改对话框的宽度以匹配按钮宽度

更新:

我通过将其添加到
onStart()
方法中,成功更改了对话框的宽度:

    int width = button.getBackground().getIntrinsicWidth();
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(getDialog().getWindow().getAttributes());
    lp.width = width;
    getDialog().getWindow().setAttributes(lp);

这会更改对话框的宽度,但会收缩按钮以保留填充。我不知道填充物是从哪里来的。

如果你不去掉正面按钮的皮肤,而是定制整个对话框,会怎么样

final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.fragment_code_dialog);

Button doneButton = (Button) dialog.findViewById(R.id.done_button);
doneButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        listener.onDialogPositiveClick(CodeDialogFragment.this);
        dialog.dismiss();
    }
});

dialog.show();
在这种情况下,正按钮(R.id.done_按钮)是布局(R.layout.fragment_code_对话框)中的一个按钮。您可以完全按照您的设计布局视图和按钮,并将其作为一个整体使用,而不必对正面按钮进行蒙皮。

只需设置

getWindow().setLayout(int width,int height)` immediately after `show()
比如说

AlertDialog.Builder builder = new AlertDialog.Builder(this);
//do other operations like inflating layout,setTile etc here
builder.show().getWindow().setLayout(600,900);'

不确定这是否有效,但如果在
setPositiveButton
之后执行
setView
会发生什么?不,这没有什么区别。
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//do other operations like inflating layout,setTile etc here
builder.show().getWindow().setLayout(600,900);'