Kiory Stores

Multiple activities on Android app

INICIO / Programación Android Multiple activities on Android app

Sometimes when we are designing our application we have the need of using more than one screen, and maybe , exchanging information from one screen to the next one. How can we work with multiple activities on Android?

 

In this post we are going to create a simple application in which we’ll have two screens and where we will pass some information from the first screen to the second one.

 

 

Captura de pantalla 2015-08-18 a las 19.26.19

Captura de pantalla 2015-08-18 a las 19.26.43

 

First of all we will have to create our example project.

 

Captura de pantalla 2015-08-18 a las 12.53.52

 

 

Captura de pantalla 2015-08-18 a las 12.54.39

 

 

Captura de pantalla 2015-08-18 a las 12.55.09

 

 

Captura de pantalla 2015-08-18 a las 12.55.27

 

 

When the project is created there are some files that are auto created so the project can be compiled and will run in the Android emulator showing a “Hello World!”  in the screen.

The project contains a simple activity (MainActivity.java) and it’s layout (activity_main.xml).
Now we will create a new activity in our project right clicking in the java package and selecting New -> Activity -> Blank Activity. In the Hierarchical Parent field we will set MainActivity as it’s parent, this will be helpful because when we open the second activity we will have a back arrow returning to it’s parent, the MainActivity.

 

Captura de pantalla 2015-08-18 a las 16.35.43

 

The main activity of our project, MainActivity.java, uses the xml layout  is called activity_main.xml and it’s located in the res/layout folder. Let’s remove the default TextView and add a Button which will open our new activity.

 

[xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="startNewActivity"
android:text="@string/button_new_activity"/>

</RelativeLayout>
[/xml]

 

You will notice that we have used a resource string as text in the Button, this string is defined in the resource file res/values/strings.xml like the following:

 

[xml]

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">TwoActivitiesExample</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="button_new_activity">Open new activity</string>

</resources>

[/xml]

 

We have also defined an onClick action for this button called startNewActivity, this method has to be declared in the activity file, in MainActivity.java.

In res/layout/activity_main.xml, we assigned the method startNewActivity() to the button using the attribute android:onClick. We will need to add this method to MainActivity.java.
 
When the user clicks the button, startNewActivity(View view) is called. 

This method has to be public, have a return void value and have a View as the only parameter, if not, the system will not match correctly this method to the onClick function defined on your xml layout file.

 

[java]

public void startNewActivity(View view){
//Start our second activity
}

[/java]

 

In our startNewActivity method we have to define a Intent using the activity Context as first parameter and the Class which the system should deliver our Intent.

 

[java]

public void startNewActivity(View view){
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(VALUE, "My custom string value");
startActivity(intent);
}

[/java]

 

The VALUE constant has been defined in the MainActivity.java.

 

[java]

private static String VALUE = "myValue";

[/java]

 

We have now all the basic to compile and run our project and navigate between this two activities, but if we have passed a string value from the MainActivity to the SecondActivity, let’s use it.

In the SecondActivity.java we will have to retrieve this string value. We have also defined the VALUE constant in this Activity.

 

[java]

String value = getIntent().getExtras().getString(VALUE);

[/java]

 

Now we can make a Toast to show this value and test our application is working fine.

 

[java]

Toast.makeText(this, value, Toast.LENGTH_LONG).show();

[/java]

 


 

MainActivity.java

[java]
package com.app.example.twoactivitiesexample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends ActionBarActivity {
private static String VALUE = "myValue";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

public void startNewActivity(View view){
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(VALUE, "My custom string value");
startActivity(intent);
}
}
[/java]

 

SecondActivity.java

[java]

package com.app.example.twoactivitiesexample;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class SecondActivity extends ActionBarActivity {
private static String VALUE = "myValue";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

String value = getIntent().getExtras().getString(VALUE);

Toast.makeText(this, value, Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

[/java]

 

You can download the example project here.

 

 


Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *