我试图获得texttinputedittext的文本,这是在一个对话框(确切地说,在设置积极的按钮部分的onCreateDialog方法),但它不起作用。我已经在StackOverflow上读了很多问题,但是没有一个对我有帮助。
保存文本的变量inputAddTunnel总是等于":
private fun getInput(): String {
val inputAddTunnel = this.layoutInflater.inflate(R.layout.dialog_add_vpn_tunnel,null).findViewById<TextInputEditText>(R.id.input_add_tunnel).getText().toString()
return inputAddTunnel
}
对话框的Xml是:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/input_add_tunnel_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:hint="@string/name_of_vpn">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/input_add_tunnel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"/>
</com.google.android.material.textfield.TextInputLayout>
编辑:这里是onCreateDialog()方法
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val builder = androidx.appcompat.app.AlertDialog.Builder(it)
// Get the layout inflater
val inflater = requireActivity().layoutInflater
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_add_vpn_tunnel, null))
// Add action buttons
.setPositiveButton(R.string.add_vpn_tunnel,
DialogInterface.OnClickListener { dialog, id ->
// Add VPN tunnel
addVpn()
})
.setNegativeButton(R.string.cancel,
DialogInterface.OnClickListener { dialog, id ->
getDialog()?.cancel()
})
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
这是addVpn方法,在onCreateDialog()中调用:
private fun addVpn() {
// TODO test function addVpn(); count doesn't work properly
val count = activity?.getPreferences(AppCompatActivity.MODE_PRIVATE)?.getInt("countTunnels", -1)
val inputAddTunnel = getInput()
// If inputAddTunnel is not equal to "", put it in getPreferences
if(inputAddTunnel != "") { //TODO test if !== is needed, not !=
activity?.getPreferences(AppCompatActivity.MODE_PRIVATE)?.
edit()?.putString("tunnel$count", inputAddTunnel).apply { }
}
// Edit the count in getPreferences to the incremented count
count?.plus(1)
if (count != null) {
activity?.getPreferences(AppCompatActivity.MODE_PRIVATE)?.getInt("countTunnels", count)
}
}
您需要从对话框视图中获取editext对象并调用getText()方法
Edittext edittext= getDialog().getView().findViewbyId(R.id.editText);
edittext.getText(); // for getting textvalue from editetxt
您正在重新生成一个全新的视图,而不是从您已经为对话框设置的视图中查询。
您应该在最初膨胀的根对话框视图上调用findViewById
。请分享您的onCreateDialog
方法,以获得更多帮助。