when the button is clicked, it is located on a fragment, and the method from MainActivity is called. after selecting from the dialog box, the method in the fragment is called again. But in this fragment, binding becomes null and (activity as MainActivity) is also null.
Fragment:
class HomeFragment : Fragment(){
private lateinit var binding: FragmentHomeBinding
private lateinit var mainActivity: MainActivity
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHomeBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mainActivity = (activity as MainActivity)
binding.addButton.setOnClickListener{
mainActivity.showDialog()
}
}
fun getText(newText: TextView){
binding.layout.addView(newText)
}
}
MainActivity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.mainContainer) as NavHostFragment
navController = navHostFragment.navController
val bottomNavigationView = binding.bottomNavigationView
setupWithNavController(bottomNavigationView,navController)
}
private fun createText(text: String, color: Int): TextView {
val textView = TextView(this)
textView.setLayoutParams(
LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
)
return textView
}
fun showDialog(){
val langArray: Array<String> = arrayOf("1", "2")
val selectedEvent = BooleanArray(langArray.size)
val langList: ArrayList<Int> = ArrayList()
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
builder.setMultiChoiceItems(langArray, selectedEvent
) { dialogInterface, i, b ->
if (b) {
langList.add(i)
langList.sort()
} else {
langList.remove(i)
}
}
builder.setPositiveButton("OK"
) { dialogInterface, i -> // Initialize string builder
if (langList.size != 1) {
val stringBuilder = StringBuilder()
for (j in langList.indices) {
stringBuilder.append(langArray[langList[j]])
if (j != langList.size - 1) {
stringBuilder.append(", ")
}
}
Toast.makeText(
applicationContext,
"Error!!!",
Toast.LENGTH_LONG
).show()
} else {
val mFragment = HomeFragment()
if (langList[0] == 0) {
} else {
mFragment.getText(createText("HELLO!", R.color.green))
}
}
}
builder.setNegativeButton("Cancel"
) { dialogInterface, i -> // dismiss dialog
dialogInterface.dismiss()
}
builder.show()
}
}
Why is binding null?