Search code examples
androidandroid-studiobuttonandroid-activity

Image button to open new Activity


I am brand new to this and my only experience programming is with PLC;s and HMI's so I apologize for not being able to figure out what is probably an easy task. but I cannot find any CURRENT videos or working examples of how to simply place an image on the main activity and have it open another activity once pressed. I'm using the newest version of Android studio 11.0 and trying to learn the Kotlin language. I have attached the code for the project that I have so far and as you can see I just started the project. Thanks in advance for any help.

Java file

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

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

XML file



        <?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">```

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="327dp"
        android:layout_height="477dp"
        android:layout_marginStart="38dp"
        android:layout_marginTop="170dp"
        android:layout_marginEnd="38dp"
        android:layout_marginBottom="84dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/trafficlightoriginal" />

</androidx.constraintlayout.widget.ConstraintLayout>
 
 
       
 
        

Solution

  • Set an onClickListener to the imagebutton then use an intent to navigate to the next activity

    class MainActivity : AppCompatActivity() {
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main)
    
    val imageButton:ImageButton=findViewById(R.id.imageButton)
    imageButton.setOnClickListener{
    startActivity(Intent(this,SecondActivity::class.java))
    }
     }
    }