0

Writing an Android app with Kotlin using Android Studio. I have several activities and each of them has similar buttons. I added global variable ACTID which references each Activity I have through the map.

Every button has android: onClick="onClick" in its XML file.

So, I tried to make a public function:

public fun allClick(view: View){
    val context = ACTIVITY_DICT[ACTID]
    val toast = Toast.makeText(context, ACTID.toString(), Toast.LENGTH_LONG)
    toast.show()
    when (view.id)
    {
        R.id.nextBtn ->    {
            val intentNext = Intent(context, ACTIVITY_DICT[ACTID+1]!!::class.java)
            context?.startActivity(intentNext)
            context?.finish()}
        R.id.backBtn ->    {
            val intentBack = Intent(context, ACTIVITY_DICT[ACTID-1]!!::class.java)
            context?.startActivity(intentBack)
            context?.finish()}
    }
}

However, I cannot set allCLick for onClick. How can I fix it? Would be grateful for any possible help.

1
  • 1
    Storing Activity references like that will leak them. You should make the context another parameter of the function, and then you wouldn't need the map. Have you looked at my answer to your question from yesterday? Commented May 31, 2020 at 20:18

1 Answer 1

1

You can make a base activity BaseActivity, implement allClick(view: View) method in it and inherit from it other activities:

class BaseActivity : AppCompatActivity() {

    public fun allClick(view: View) {
        val context = ACTIVITY_DICT[ACTID]
        val toast = Toast.makeText(context, ACTID.toString(), Toast.LENGTH_LONG)
        toast.show()
        when (view.id) {
            R.id.nextBtn -> {
                val intentNext = Intent(context, ACTIVITY_DICT[ACTID+1]!!::class.java)
                context?.startActivity(intentNext)
                context?.finish()
            }
            R.id.backBtn -> {
                val intentBack = Intent(context, ACTIVITY_DICT[ACTID-1]!!::class.java)
                context?.startActivity(intentBack)
                context?.finish()
            }
        }
    }
}

Also add android: onClick="allClick" for every button in its XML file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.