使用 setView(int layoutResId) 时如何从 AlertDialog 获取膨​​胀视图?

How to get the inflated view from AlertDialog when using setView(int layoutResId)?

我使用此代码创建自定义 AlertDialog:

val dialog = AlertDialog.Builder(context)
            .setView(R.layout.layout)
            .create()

问题是我无法获得放大的视图。 dialog.findViewById(R.id.a_view_in_the_layout) returns 空。

或者,我可以使用 .setView(View.inflate(context, R.layout.layout, null),但这有时会使对话框填满屏幕,占用的 space 多于 setView(int layoutResId)

自己扩充布局(它的 Java 代码,但我想你知道该怎么做):

AlertDialog.Builder dialog = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View view = inflater.inflate( R.layout.layout, null );
dialog.setView(view);
dialog.create().show();

您的扩充视图现在是 view,您可以使用它在其中查找其他视图,例如:

EditText editText = view.findViewById(R.id.myEdittext);

而不是使用 alert dialog 使用 simple Dialog 它简单且非常简单

final Dialog dialog = new Dialog(context);
        dialog.setContentView((R.layout.layout);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        TextView tvTitle = (TextView) dialog.findViewById(R.id.tvTitle);
        tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

您不必为视图充气。

试试这个;

View dialogView; //define this as a gobal field

dialogView = LayoutInflater.from(context).inflate(R.layout.your_view, null);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setView(dialogView);

View yourView = dialogView.findViewById(R.id.a_view_in_the_layout);
TextView yourTextView = dialogView.findViewById(R.id.a_textView_in_the_layout);
Button yourButton = dialogView.findViewById(R.id.a_button_in_the_layout);

如果我没记错的话,create 设置了 Dialog,但它的布局在需要显示之前不会膨胀。然后先尝试调用 show,然后找到您要查找的视图。

val dialog = AlertDialog.Builder(context)
            .setView(R.layout.layout)
            .create()

dialog.show() // Cause internal layout to inflate views
dialog.findViewById(...)