第一次在这里提问希望我能得到答案:(我是Kotlin的新手,我用C++编程已经3年多了,现在我转向了移动应用程序所以我的问题是:我试图在片段中创建对话框,允许用户插入自由字段文本。当他点击加号按钮时,它应该打开具有自由字段文本区域的对话框,允许他插入文本;添加";或";取消";当我运行程序时,我在对话框中看到的只是按钮";添加";以及";取消";但是我看不到文本字段栏本身。
但是当我将视图从fragment_view更改为dialog_view时,我确实看到了文本字段栏。(我希望我的问题解释清楚(这是我的片段(fragment_shopping_list(代码:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_shopping_list, container, false)
val addItem_button = view.findViewById<com.google.android.material.floatingactionbutton.FloatingActionButton>(R.id.fab_shoppiglist)
addItem_button.setOnClickListener {
val dialog = AlertDialog.Builder(getContext())
val tempView = inflater.inflate(R.layout.dialog_shoppinglist,null )
dialog.setPositiveButton("Add"){ _: DialogInterface, _: Int ->
}
dialog.setNegativeButton("Cancel"){ _: DialogInterface, _: Int->
}
dialog.show()
}
return view
}
这是我的对话框(dialog_shoppinglist(代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/et_Itemlist"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
val dialog = context?.let { AlertDialog.Builder(it) }
dialog?.setView(R.layout.dialog_shoppinglist)
dialog?.setPositiveButton("Add"){ _: DialogInterface, _: Int ->
}
dialog?.setNegativeButton("Cancel"){ _: DialogInterface, _: Int->
}
dialog?.show()
试试这个:
val tempView = inflater.inflate(R.layout.dialog_shoppinglist, null)
val dialog = AlertDialog.Builder(getContext())
.setPositiveButton("Add"){ _: DialogInterface, _: Int ->
}.setNegativeButton("Cancel"){ _: DialogInterface, _: Int->
}.create()
dialog.show()
dialog.window!!.setContentView(tempView)
// the following is optional
dialog.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
dialog.window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
在点击按钮时添加此项:
val text = tempView.findViewById<EditText>(R.id.et_Itemlist).text.toString
您可以在对话框中获取输入的文本。