How to start a new Activity

| | Comments (0)

Android has a weird way of constructing UI. At least I haven't got used to it.

First of all, AndroidManifest.xml must have activities listed:


<activity android:name=".FirstActivity" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>


<activity android:name=".SecondActivity" android:label="Second Activity">
    <intent-filter>
        <action android:name="com.example.app.activities.SECOND" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

There are several ways to set the components (action, type, category) of Intent, below are the 2 easiest ways.

Intent i = new Intent();
i.setAction(“com.example.app.activities.SECOND”);

Or this:

i.setClass(getApplicationContext(), SecondView.class);

Create a bundle to pass data to the new activity:

Bundle bundle = new Bundle();
bundle.putString("TEXT", "Lorem ipsum");
i.putExtras(bundle);

To start the activity:

startActivity(i);

To get the data from the bundle that’s passed to our new activity:

Bundle bundle = getIntent().getExtras();
String prompt = bundle.getString("TEXT");

Leave a comment