代码之家  ›  专栏  ›  技术社区  ›  Dewey Reed

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

  •  0
  • Dewey Reed  · 技术社区  · 7 年前

    我使用此代码创建自定义警报对话框:

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

    0 回复  |  直到 7 年前
        1
  •  1
  •   dominicoder    7 年前

    如果我没记错, create show 首先,然后,找到你要找的风景。

    val dialog = AlertDialog.Builder(context)
                .setView(R.layout.layout)
                .create()
    
    dialog.show() // Cause internal layout to inflate views
    dialog.findViewById(...)
    
        2
  •  2
  •   Tanveer Munir    7 年前

    而不是使用 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) {
    
                }
            });
    

        3
  •  1
  •   Chris623    7 年前

    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
  •  0
  •   parliament    7 年前

    试试这个;

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