-1

I would like to click an image button and have it open a new activity and change the text view of that activity. Here's what I have so far, to open the new activity:

val bad = findViewById<ImageButton>(R.id.bad)
        bad.setOnClickListener {
            val intent = Intent(this, HomeActivity::class.java)
            startActivity(intent)
        }

but I don't know where to add the info for changing the TextView text onclick. I tried it this way and it worked, but the textview is in the same XML.

fun onClick(view: View) {
        val text = findViewById<TextView>(R.id.textView) as TextView
        text.text = "Button clicked"

    }

Yes I've done extensive research on this, and even read similar posts on here. But I'm still lost. I would like a definitive answer for my specific question... so yea. Thank you in advance for your help!

Ryan M
  • 11,512
  • 21
  • 38
  • 50
  • 1
    Does this answer your question? [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – Ryan M Aug 16 '20 at 07:22

1 Answers1

0

There's an answer here about passing data between activities

You basically want to add a String extra to your Intent, and then grab it in the new Activity and set your TextView to use that value. onCreate is a good place to do it


val bad = findViewById<ImageButton>(R.id.bad)
        bad.setOnClickListener {
            val intent = Intent(this, HomeActivity::class.java)
            // put the data in
            intent.putExtra("MY_TEXT", "whatever text you want in the TextView")
            startActivity(intent)
        }
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val textView = findViewById<TextView>(R.id.textView) as TextView
    // get the data out
    val newText = intent.getStringExtra("MY_TEXT")
    // do whatever (if you didn't add the extra newText will be null)
    textView.text = newText
}
cactustictacs
  • 4,293
  • 1
  • 4
  • 13