android-er
android-er

Reputation: 13

Android Click Listener Behaviour

Screen Grab Android

This might be a stupid question.

In Android, when I swap two TextViews why don't their onClickListeners get swapped too (in working)?

The object hash codes are swapped though and so is the mListenerInfo object. (Part of View Class)

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    var textView1 = TextView(this)
    var textView2 = TextView(this)

    textView1.text = "T1"
    textView2.text = "T2"

    //linear is a LinearLayout via kotlinx access

    linear.addView(textView1)
    linear.addView(textView2)

    textView1.setOnClickListener({
        Toast.makeText(applicationContext, it.hashCode().toString(), Toast.LENGTH_SHORT).show()
    })

    textView2.setOnClickListener({
        Toast.makeText(applicationContext, it.hashCode().toString(), Toast.LENGTH_SHORT).show()
    })

    val x = textView1
    textView1 = textView2
    textView2 = x

    Toast.makeText(applicationContext, textView1.hashCode().toString() +"\n" + textView1.text, Toast.LENGTH_SHORT)
        .show()

    Toast.makeText(applicationContext, textView2.hashCode().toString() +"\n" + textView2.text, Toast
        .LENGTH_SHORT).show()

  }
}

The textViews and their corresponding properties get swapped, so textView1.text returns "T2", but on clicking T1 on screen we still get the old hashcode.

Am I doing something wrong here?

Upvotes: 1

Views: 120

Answers (1)

Cililing
Cililing

Reputation: 4753

Because keyword "it" and all others variables in lambdas are final.

textView1.setOnClickListener {
    Toast.makeText(applicationContext, it.hashCode().toString(), Toast.LENGTH_SHORT).show()
}

So, your code it.hashCode() refers to specific function of immutable object in your memory. Even if you swap t1 with t2 you will call proper object and even proper listener, but it still refers to old object.

After swapping those views you should fix your listeners (for example by creating new ones).

Upvotes: 1

Related Questions