javaandroidkotlinbuttonclickandroid-imagebutton

Android ImageButton event does not execute all actions upon first click


I have a button to delete all data on my activity screen (a chart, database data and a textview) and to display a toast. Pressing the button does everything apart from getting rid of the textview, which only happens upon a second press. The code is in onCreate. Why is this happening and how can I fix it? Thank you :)

findViewById<ImageButton>(R.id.delete_btn).setOnClickListener {
   pieChart.visibility = View.GONE
   textView.visibility = View.GONE
   appsViewModel.removeAll()
   Toast.makeText(this, "Successfully deleted all", Toast.LENGTH_SHORT).show()
}

Solution

  • As @mayurgajra made me realise, some other code interfered with the changes in the textView. I managed to fix this with a boolean. I set it to true within the ImageButton event, and now I only modify the textview visibility in my other code if the boolean is false.

    private var deleted: Boolean = false
    override fun onCreate(savedInstanceState: Bundle?) {
            ...
            findViewById<ImageButton>(R.id.delete_btn).setOnClickListener {
                pieChart.visibility = View.GONE
                totalUsage.visibility = View.GONE
                deleted = true
                appsViewModel.removeAll()
                Toast.makeText(this, "Successfully deleted all", Toast.LENGTH_SHORT).show()
            }
    }
    
    private fun otherMethod(){
               ...
               if (!deleted) {
                      totalUsage.text = "Total usage today: $hour"
                      totalUsage.visibility = View.VISIBLE
               }
    }