[英]How access another fragment from a fragment in Android using Kotlin?
val dialog = AlertDialog.Builder(activity as Context)
dialog.setTitle("Confirmation")
dialog.setMessage("Are you sure you want to log out?")
dialog.setPositiveButton("YES"){ text, listener ->
sharedPreferences.edit().clear().apply()
println("Shared preferences cleared")
println("Logged out")
val intent = Intent(activity as Context, LoginActivity::class.java)
startActivity(intent)
}
dialog.setNegativeButton("NO"){text,listener ->
val homeFragment = HomeFragment()
val beginTransaction = activity!!.supportFragmentManager.beginTransaction()
beginTransaction.replace(R.id.frameLayout, homeFragment)
beginTransaction.commit()
activity!!.navigationView.setCheckedItem(R.id.home_screen)
println("Home title set")
activity!!.actionBar!!.title = "Home"
}
dialog.create()
dialog.show()
當用戶單擊“否”按鈕時,我想 go 主頁片段。 我被定向到 Home Fragment,但對話框沒有消失,當我再次單擊“否”時,應用程序崩潰,並在行上給出 Null 指針異常:
val beginTransaction = activity!!.supportFragmentManager.beginTransaction()
到達主頁片段時如何刪除對話框? 請幫忙。
調用dialog.dismiss();
在提交事務之前
並且在轉移到另一項活動之前
val builder = AlertDialog.Builder(activity as Context)
.setTitle("Confirmation")
.setMessage("Are you sure you want to log out?")
.setPositiveButton("YES"){ dialog, _ ->
sharedPreferences.edit().clear().apply()
println("Shared preferences cleared")
println("Logged out")
dialog.dismiss()
val intent = Intent(activity as Context, LoginActivity::class.java)
startActivity(intent)
}
.setNegativeButton("NO"){dialog,_ ->
val homeFragment = HomeFragment()
val beginTransaction = activity!!.supportFragmentManager.beginTransaction()
beginTransaction.replace(R.id.frameLayout, homeFragment)
dialog.dismiss()
beginTransaction.commit()
activity!!.navigationView.setCheckedItem(R.id.home_screen)
println("Home title set")
activity!!.actionBar!!.title = "Home"
}
.show()
問題是,作為 clicklisteners 的參數,您會得到一個DialogInterface
object。 object 有一個dismiss()
方法。 您需要調用那個來關閉對話框。
val dialog = AlertDialog.Builder(activity as Context)
dialog.setTitle("Confirmation")
dialog.setMessage("Are you sure you want to log out?")
dialog.setPositiveButton("YES"){ text, listener ->
sharedPreferences.edit().clear().apply()
println("Shared preferences cleared")
println("Logged out")
val intent = Intent(activity as Context, LoginActivity::class.java)
startActivity(intent)
}
dialog.setNegativeButton("NO"){dlgInterface: DialogInterface,listener ->
val homeFragment = HomeFragment()
val beginTransaction = activity?.supportFragmentManager.beginTransaction()
beginTransaction.replace(R.id.frameLayout, homeFragment)
beginTransaction.commit()
activity?.navigationView.setCheckedItem(R.id.home_screen)
println("Home title set")
activity?.actionBar?.title = "Home"
dlgInterface.dismiss()
}
dialog.create()
dialog.show()
也請停止使用強制解包!!
. Kotlin 有這種安全展開的魔力?
它可以挽救生命。 用它;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.