Intent in Android using Kotlin
What is Intent ?
Intent is a messaging object used to request an action from application components like activity,service, broadcast receiver
There are 2 types of Intents
- Explict Intent
- Implict Intent
Explict Intent
Explict intents are used to switch between the activities , it can also pass data from one activity to another.
activity_first.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FirstActivity"
android:orientation="vertical"> <Button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="Explicit Intent Example"/> </LinearLayout>
FirstActivity.kt
package com.example.kotlinsampleproject import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_first.* class FirstActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_first) button.setOnClickListener {intent = Intent(this,SecondActivity::class.java) startActivity(intent); } } }
Implict Intent
Implict intent doesnt directly specify the android component which should be called, it tells the action to be performed,
we can simply define implicity intent as the component where next action as is known and action is performed in the same page without calling other android components.
Example using Kotlin
package com.example.kotlinsampleproject import android.content.Intent import android.net.Uri import android.support.v7.app.AppCompatActivity import android.os.Bundle class SecondActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) //Example for implict intent
intent = Intent(Intent.ACTION_VIEW,
Uri.parse("https://sushmithan.blogspot.com")) startActivity(intent); } }
Output :
Happy Reading 😊
Thank You
Sushmitha N
Hi there ! Im a experienced android developer with 4years of revelant exprience.My Skills include Android,Core Java ,Oops and Kotlin.
Youtube Channel : SDK Book
Comments
Post a Comment