Intent:
Intent is a message passing object and plays vital role in providing communication between android elements.
By using intent, we can do some operations include
1) Opening an activity
2) Navigating from one activity to another activity
3) Sending data from activity to activity
4) Starting a service
5) Sending a broadcast
|
|
|
etc
Navigating from one activity to another:
For navigating from one activity to another, the steps are as follows
1) First, we need to create an object of intent by passing the current activity object and destination activity
2) Call method startActivity by passing the intent object as parameter.
3) Optional step – current activity can be closed by using finish() method.
Ex: Intent i = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i);
finish(); // optional
Create an Android application to move from one activity to another activity
XML:
activity_source.xml:
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity=”center”
android:orientation=”vertical”>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:onClick=”moveToNext”
android:text=”Move to Next Activity” />
</LinearLayout>
activity_destination.xml:
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity=”center”
android:orientation=”vertical”>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”This is destination Activity”
android:textSize=”25sp”
android:textStyle=”bold” />
</LinearLayout>
Java:
SourceActivity.class:
public class SourceActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_source);
}
public void moveToNext(View v){
Intent i = new Intent(SourceActivity.this, DestinationActivity.class);
startActivity(i);
finish(); // optional
}
}
DestinationActivity.class
public class DestinationActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_destination);
}
}
AndroidManifest.xml:
Inside <application> tag
<activity android:name=”.SourceActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<activity android:name=”.DestinationActivity”></activity>