Home > Enterprise >  In Kotlin, how can I choose which textview a button should show the text?
In Kotlin, how can I choose which textview a button should show the text?

Time:03-16

I have two textviews in Kotlin, say Textview No 1 and Textview No. 2. I want buttons to show their text in one of the textviews that I select. E.g. Button "A" to show the text A in the first textview when I click the textview No. 1, and Button "B" to show the text B in the textview No. 2. It is similar to a calculator, just that calculators have only one textview. I am interested to show only the text, not mathematical calculations.

Thank you

CodePudding user response:

You should be able to do something like this:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val textViewA: TextView? = view.findViewById(R.id.textViewA)
        val textViewB: TextView? = view.findViewById(R.id.textViewB)
        val buttonA: Button? = view.findViewById(R.id.buttonA)
        val buttonB: Button? = view.findViewById(R.id.buttonB)

        buttonA?.setOnClickListener {
            textViewA?.text = buttonA.text
        }
        buttonB?.setOnClickListener {
            textViewB?.text = buttonB.text
        }
    }

CodePudding user response:

Think of it this way.

What are the events you are handling? Event 1: Click of button 1 Event 2: Click of button 2

on click of Event 1 what do you want to do -> change text in textview 1

so use


        buttonA?.setOnClickListener { // handling the button click(event 1)
            textViewA?.text = buttonA.text (putting the value in text on button click )
        }

Similarly for button 2 click

  • Related