首页 > 解决方案 > 使用 setView(int layoutResId) 时如何从 AlertDialog 获取膨​​胀视图?

问题描述

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

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

问题是我无法获得膨胀的视图。dialog.findViewById(R.id.a_view_in_the_layout)返回空值。

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

标签: androidandroid-alertdialogandroid-dialog

解决方案


而不是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) {

            }
        });

您不必为视图充气。


推荐阅读