【问题标题】:How to get the inflated view from AlertDialog when using setView(int layoutResId)?使用 setView(int layoutResId) 时如何从 AlertDialog 获取膨​​胀视图?
【发布时间】:2019-02-26 06:00:18
【问题描述】:

我使用这段代码来创建一个自定义的 AlertDialog:

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

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

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

【问题讨论】:

  • @NileshRathod 谢谢。子类化 Dialog 似乎是一个可行的选择,但我们将失去 AlertDialog 提供的其他很酷的功能。
  • dialog.findViewById crashes the app 你遇到了什么错误
  • 当出现“应用程序崩溃”时,请务必澄清 - 没有更多信息,没有人可以帮助您诊断问题。
  • @dominicoder 我已经编辑了这个问题。它返回 null,我找不到其他方法来查找视图。

标签: android android-alertdialog android-dialog


【解决方案1】:

不要使用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) {

            }
        });

您不必为视图充气。

【讨论】:

    【解决方案2】:

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

    val dialog = AlertDialog.Builder(context)
                .setView(R.layout.layout)
                .create()
    
    dialog.show() // Cause internal layout to inflate views
    dialog.findViewById(...)
    

    【讨论】:

      【解决方案3】:

      只需自己扩展布局(它的 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);
      

      【讨论】:

        【解决方案4】:

        试试这个;

        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);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-26
          相关资源
          最近更新 更多