1

I'm just making my first steps with Android Studio and Kotlin. Unfortunately I despair of a simple application here.

I would like a certain function to be addressed by an onClick event of a button and then to give a toast.

But in my current setup this seems not to work. I will post the code for it. So once my MainActivity.kt and activity_main.xml

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

    }

    fun startDashboard(view: View) {
        Toast.makeText(this@MainActivity, "called startDasboard",Toast.LENGTH_SHORT).show()
    }
}
   <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.1" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.9" />

    <Button
        android:id="@+id/startButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:onClick="startDashboard"
        android:text="@string/startButtonText"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline" />



    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="625dp" />


</androidx.constraintlayout.widget.ConstraintLayout>
Lsander
  • 53
  • 1
  • 4

1 Answers1

0

The code looks fine in my perspective. However, since you said that it doesn't show the toast, try this in the meantime.

In your MainActivity.kt

// below the setContentView()

val button: Button = findViewById(R.id.startButton)

button.setOnClickListener{ view ->
    startDashboard(view)
}
Andrew Chelix
  • 1,012
  • 11
  • 16
  • 1
    Thank you for your help. I am now successfully using the method to implement an onClick listener. Now I see the toast too. – Lsander Sep 01 '20 at 10:02