以下是MainActivity onCreate方法中的AlertDialog:
import kotlinx.android.synthetic.main.dialog.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fab.setOnClickListener { view ->
AlertDialog.Builder(this@MainActivity)
.setView(LayoutInflater.from(this@MainActivity).inflate(R.layout.dialog, null))
.setPositiveButton("OK") {dialog, i ->
Toast.makeText(
this@MainActivity, dialogEditText.text, Toast.LENGTH_SHORT)
.show()
dialog.dismiss()
}.show()
}
}
}
这是对话框布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/dialogEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
</RelativeLayout>
然而,最后,我收到了这个错误:
java.lang.IllegalStateException:dialogEditText不能为null
但我填写了输入......这里有什么问题?
答案 0 :(得分:2)
这是我找到的解决方案。谢谢你的帮助!
val view = LayoutInflater.from(this@MainActivity).inflate(R.layout.dialog, null)
AlertDialog.Builder(this@MainActivity)
.setView(view)
.setPositiveButton("OK") {dialog, i ->
Toast.makeText(
this@MainActivity, view.dialogEditText.text, Toast.LENGTH_SHORT)
.show()
dialog.dismiss()
}.show()
答案 1 :(得分:-1)
import kotlinx.android.synthetic.main.dialog.*
val dialogBuilder = AlertDialog.Builder(this)
val inflater = this.layoutInflater
val dialogView = inflater.inflate(R.layout.dialog, null)
dialogBuilder.setView(dialogView)
val editText = dialogView.findViewById<View>(R.id.dialogEditText) as EditText
dialogBuilder.setTitle("Your Dialog")
dialogBuilder.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, whichButton ->
Toast.makeText(this@MainActivity, editText.text.toString(), Toast.LENGTH_SHORT)
.show()
dialog.dismiss()
})
val b = dialogBuilder.create()
b.show()