How to start an Activity on Click in Kotlin using Android Studio?
In this tutorial we will learn how to start a new activity when a button is clicked(you can also implement this on item click or something else).
Step 1: Create a new Project with Kotlin Support OR open a new Project
Step 2: Create a new Activity(when button is click we will go to that activity)
Step 3: Code
activity_main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"android:orientation="vertical"android:gravity="center"tools:context=".MainActivity"><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Start New Activity"/></LinearLayout>
MainActivity.kt
package com.blogspot.devofandroid.kotlinpracticeimport android.content.Intentimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)//to change title of activity(optional)val actionBar = supportActionBaractionBar!!.title = "Main Activity"//buttonval mButton = findViewById(R.id.button) as Button//button clickmButton.setOnClickListener {val intent = Intent(this , NewActivity::class.java)startActivity(intent)}}}
activity_new.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"android:orientation="vertical"android:gravity="center"tools:context=".NewActivity"><TextViewandroid:text="New Activity"android:textStyle="bold"android:textSize="30sp"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>
NewActivity.kt
package com.blogspot.devofandroid.kotlinpracticeimport android.support.v7.app.AppCompatActivityimport android.os.Bundleclass NewActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_new)//to change title of activity(optional)val actionBar = supportActionBaractionBar!!.title = "New Activity"}}
Note: You can also use:
startActivity(Intent(this , NewActivity::class.java));
0 Response to "Starting Activity With (Kotlin) - Android Studio"