Search code examples
androidandroid-studiokotlinonclicklistener

How to get two text inputs to show in one message with OnClickListener in Android Kotlin?


I have two text input fields and a button. I managed to implement that, when both textfields are filled and I click the button, a message showing the input from the first text field is showing.

What I would like to do is to implement that when both textfields are filled and I click the button, a message showing the input from the both text fields (in one message) is showing.

Could anyone help me to do that?/ Has anyone done something similar? Thank you in advance!

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    
    val autotextView
            = findViewById<AutoCompleteTextView>(R.id.autoTextViewStart)
    val autotextViewZiel
            = findViewById<AutoCompleteTextView>(R.id.autoTextViewZiel)


    // Get the array of languages
    val languages
            = resources.getStringArray(R.array.Languages)
    // Create adapter and add in AutoCompleteTextView
    val adapter
            = ArrayAdapter(this,
        android.R.layout.simple_list_item_1, languages)
    autotextView.setAdapter(adapter)
    autotextViewZiel.setAdapter(adapter)


    val button
            = findViewById<Button>(R.id.btn); if (button != null)
    {
        button.setOnClickListener(View.OnClickListener {
            val enteredText = autotextView.getText()
            Toast.makeText(this@MainActivity, enteredText, Toast.LENGTH_SHORT).show()
        })
    }

Solution

  • If you are looking to concatenate 2 strings in Kotlin, there are various ways. Please find them here and here. Simple one you can do as follows:

    button.setOnClickListener(View.OnClickListener {
                val enteredText = autotextView.getText() + "  " +autotextViewZiel.getText()
                Toast.makeText(this@MainActivity, enteredText, Toast.LENGTH_SHORT).show()
            })