无法初始化Kotlin中的对话框中的按钮

我在里面有一个带有AlertDiaolog的浮动操作按钮监听AlertDiaolog 。 我想用XML中的按钮。 如果我想为他们写一个onClickListener()

所以在Java中,我必须像这样初始化它:

 butAdd = (Button)dialog.findViewById(R.id.btn_add) butAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Some code } 

但是当我尝试使用:

 var butAdd = dialog?.findViewById(R.id.btn_add) as Button; 

在Kotlin这是不正确的

那么有什么建议如何解决呢? 听众怎么了?

这里是我的浮动动作按钮的代码:

 fab?.setOnClickListener { diaolg = AlertDialog.Builder(this@Cards) val linearlayout = getLayoutInflater().inflate(R.layout.add_password, null) diaolg?.setView(linearlayout) ?.setTitle("Add a new password") ?.setCancelable(true) var login = findViewById(R.id.login) as EditText var password = findViewById(R.id.password) as EditText var title = findViewById(R.id.title) as EditText var butAdd = diaolg?.findViewById(R.id.btn_add) as Button var butCancel = diaolg?.findViewById(R.id.btn_cancel) as Button butAdd.setOnClickListener(View.OnClickListener { fun onClick(v:View){ } }) butCancel.setOnClickListener(View.OnClickListener { fun onClick(v:View){ } }) diaolg?.create() diaolg?.show() } 

请通过使用找到id

  var butAdd = linearlayout.findViewById<Button>(R.id.btn_add) as Button; 

无论你在什么类没有findViewById方法。 你必须在膨胀的布局上找到findViewById ,所以:

  var login = linearLayout.findViewById(R.id.login) as EditText 

另外,我不认为你需要有? 在对话框中,它不能为空。 另外,我会让你的意见val s而不是var s。

在你的Activity中导入这一行

 <Button android:id="@+id/btn_submit" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="submit" /> 

在你的Activity中导入这一行

//使用主源集的R.layout.activity_main

// activity_main是你的布局文件名

导入kotlinx.android.synthetic.main.activity_main。*

  btn_submit.setOnClickListener { Toast.makeText(this, "hello", Toast.LENGTH_LONG).show(); } 

它为我工作。