Você está na página 1de 11

Starting Another Activity

This lesson teaches you to:


1. Respond to the Send Button
2. Build an Intent
3. Start the Second Activity
4. Create the Second Activity
5. Receive the Intent
6. Display the Message
AIter completing the previous lesson, you have an app that shows an
activity (a single screen) with a text Iield and a button. In this lesson,
you`ll add some code to MainActivity that starts a new activity when the
user clicks the Send button.
1. Respond to the Send Button
To respond to the button's on-click event, open the activitymain.xml
layout Iile and add the android:onClick attribute to the Button~
element:
Button
android:layoutwidth"wrapcontent"
android:layoutheight"wrapcontent"
android:text"string/buttonsend"
android:onClick"sendMessage" /~
The android:onClick attribute`s value, "sendMessage", is the name oI a
method in your activity that the system calls when the user clicks the
button.
Open the MainActivity class (located in the project's src/ directory) and
add the corresponding method:
/** Called when the user clicks the Send button */
public void sendMessage(View view)
// Do something in response to button
}
This requires that you import the View class:
import android.view.View;
Tip: In Eclipse, press Ctrl ShiIt O to import missing classes (Cmd
ShiIt O on Mac).
In order Ior the system to match this method to the method name
given to android:onClick, the signature must be exactly as shown.
SpeciIically, the method must:
1. Be public
2. Have a void return value
3. Have a View as the only parameter (this will be
the View that was clicked)
Next, you`ll Iill in this method to read the contents oI the text Iield and
deliver that text to another activity.
2. Build an Intent
An Intent is an object that provides runtime binding between separate
components (such as two activities). The Intent represents an app`s
"intent to do something." You can use intents Ior a wide variety oI tasks,
but most oIten they`re used to start another activity.
Inside the sendMessage() method, create an Intent to start an activity
called DisplayMessageActivity:
Intent intent new Intent(this, DisplayMessageActivity.class);
The constructor used here takes two parameters:
A Context as its Iirst parameter (this is used because the Activity class is
a subclass oI Context)
The Class oI the app component to which the system should deliver the
Intent (in this case, the activity that should be started)
Note: The reIerence to DisplayMessageActivity will raise an error iI
you`re using an IDE such as Eclipse because the class doesn`t exist yet.
Ignore the error Ior now; you`ll create the class soon.
An intent not only allows you to start another activity, but it can carry a
bundle oI data to the activity as well. Inside the sendMessage() method,
use IindViewById() to get the EditText element and add its text value to
the intent:
Intent intent new Intent(this, DisplayMessageActivity.class);
EditText editText (EditText) IindViewById(R.id.editmessage);
String message editText.getText().toString();
intent.putExtra(EXTRAMESSAGE, message);
Note: You now need import statements Ior android.content.Intent and
android.widget.EditText. You'll deIine the EXTRAMESSAGE
constant in a moment.
An Intent can carry a collection oI various data types as key-value pairs
called extras. The putExtra() method takes the key name in the Iirst
parameter and the value in the second parameter.
In order Ior the next activity to query the extra data, you should deIine
the key Ior your intent's extra using a public constant. So add the
EXTRAMESSAGE deIinition to the top oI the MainActivity class:
public class MainActivity extends Activity
public Iinal static String EXTRAMESSAGE
"com.example.myIirstapp.MESSAGE";
...
}
It's generally a good practice to deIine keys Ior intent extras using your
app's package name as a preIix. This ensures they are unique, in case
your app interacts with other apps.
3. Start the Second Activity
To start an activity, call startActivity() and pass it your Intent. The
system receives this call and starts an instance oI the Activity speciIied
by the Intent.
With this new code, the complete sendMessage() method that's invoked
by the Send button now looks like this:
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
Now you need to create the DisplayMessageActivity class in order Ior
this to work.
4. Create the Second Activity
Figure 1. The new activity wizard in Eclipse.
To create a new activity using Eclipse:Click New in the toolbar.
1. In the window that appears, open the Android Iolder and select
Android Activity. Click Next.
2. Select BlankActivity and click Next.
3. Eill in the activity details:
o Project: MyEirstApp
o Activity Name: DisplayMessageActivity
o Layout Name: activitydisplaymessage
o Title: My Message
o Hierarchial Parent: com.example.myfirstapp.MainActivity
o Navigation Type: None
Click Finish.
4. Create the Second Activity
Figure 1. The new activity wizard in Eclipse.
To create a new activity using Eclipse:Click New in the toolbar.
1. In the window that appears, open the Android Iolder and select
Android Activity. Click Next.
2. Select BlankActivity and click Next.
3. Eill in the activity details:
o Project: MyEirstApp
o Activity Name: DisplayMessageActivity
o Layout Name: activitydisplaymessage
o Title: My Message
o Hierarchial Parent: com.example.myfirstapp.MainActivity
o Navigation Type: None
Click Finish.
4. Create the Second Activity
Figure 1. The new activity wizard in Eclipse.
To create a new activity using Eclipse:Click New in the toolbar.
1. In the window that appears, open the Android Iolder and select
Android Activity. Click Next.
2. Select BlankActivity and click Next.
3. Eill in the activity details:
o Project: MyEirstApp
o Activity Name: DisplayMessageActivity
o Layout Name: activitydisplaymessage
o Title: My Message
o Hierarchial Parent: com.example.myfirstapp.MainActivity
o Navigation Type: None
Click Finish.
II you're using a diIIerent IDE or the command line tools, create a new
Iile named DisplayMessageActivity.java in the project's src/ directory,
next to the original MainActivity.java Iile.
Open the DisplayMessageActivity.java Iile. II you used Eclipse to create
this activity:
The class already includes an implementation oI the required onCreate()
method.
There's also an implementation oI the onCreateOptionsMenu() method,
but you won't need it Ior this app so you can remove it.
There's also an implementation oI onOptionsItemSelected() which
handles the behavior Ior the action bar's Up behavior. Keep this one the
way it is.
Because the ActionBar APIs are available only on HONEYCOMB (API
level 11) and higher, you must add a condition around the
getActionBar() method to check the current platIorm version.
Additionally, you must add the SuppressLint("NewApi") tag to the
onCreate() method to avoid lint errors.
The DisplayMessageActivity class should now look like this:
public class DisplayMessageActivity extends Activity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Make sure we're running on Honeycomb or higher to use
ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
II you used an IDE other than Eclipse, update your
DisplayMessageActivity class with the above code.
All subclasses oI Activity must implement the onCreate() method. The
system calls this when creating a new instance oI the activity. This
method is where you must deIine the activity layout with the
setContentView() method and is where you should perIorm initial setup
Ior the activity components.
Note: II you are using an IDE other than Eclipse, your project does not
contain the activitydisplaymessage layout that's requested by
setContentView(). That's OK because you will update this method later
and won't be using that layout.
Add the title string
II you used Eclipse, you can skip to the next section, because the
template provides the title string Ior the new activity.
II you're using an IDE other than Eclipse, add the new activity's title to
the strings.xml Iile:
<resources>
...
<string name="title_activity_display_message">My Message</string>
</resources>
Add it to the manifest
All activities must be declared in your maniIest Iile,
AndroidManiIest.xml, using an activity~ element.
When you use the Eclipse tools to create the activity, it creates a deIault
entry. II you're using a diIIerent IDE, you need to add the maniIest entry
yourselI. It should look like this:
<application ... >
...
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
The android:parentActivityName attribute declares the name oI this
activity's parent activity within the app's logical hierarchy. The system
uses this value to implement deIault navigation behaviors, such as Up
navigation on Android 4.1 (API level 16) and higher. You can provide
the same navigation behaviors Ior older versions oI Android by using the
Support Library and adding the meta-data~ element as shown here.
Note: Your Android SDK should already include the latest Android
Support Library. It's included with the ADT Bundle but iI you're using a
diIIerent IDE, you should have installed it during the Adding PlatIorms
and Packages step. When using the templates in Eclipse, the Support
Library is automatically added to your app project (you can see the
library's JAR Iile listed under Android Dependencies). II you're not
using Eclipse, you need to manually add the library to your project
Iollow the guide Ior setting up the Support Library then return here.
II you're developing with Eclipse, you can run the app now, but not
much happens. Clicking the Send button starts the second activity but it
uses a deIault "Hello world" layout provided by the template. You'll
soon update the activity to instead display a custom text view, so iI
you're using a diIIerent IDE, don't worry that the app won't yet compile.
5. Receive the Intent
Every Activity is invoked by an Intent, regardless oI how the user
navigated there. You can get the Intent that started your activity by
calling getIntent() and retrieve the data contained within it.
In the DisplayMessageActivity class`s onCreate() method, get the intent
and extract the message delivered by MainActivity:
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
6. Display the Message
To show the message on the screen, create a TextView widget and set
the text using setText(). Then add the TextView as the root view oI the
activity`s layout by passing it to setContentView().The complete
onCreate() method Ior DisplayMessageActivity now looks like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message =
intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
You can now run the app. When it opens, type a message in the text
Iield, click Send, and the message appears on the second activity.
Figure 2. Both activities in the Iinal app, running on
You can now run the app. When it opens, type a message in the text
Iield, click Send, and the message appears on the second activity.
Figure 2. Both activities in the Iinal app, running on
You can now run the app. When it opens, type a message in the text
Iield, click Send, and the message appears on the second activity.
Figure 2. Both activities in the Iinal app, running on

Você também pode gostar