After completing the previous lesson (creating a simple user interface), we already have an app (app) that shows an activity (an interface) that contains a text field and a button. In this lesson, we will add some new code to the MyActivity
start of a new activity when the user clicks the Send button.
Response Send button
1 Open the Content_my.xml file in the Res/layout directory in Android Studio.
2 Add the Android:onclick property to the Button label.
Res/layout/content_my.xml
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" android:onClick="sendMessage" />
android:onclick
The value of the property is the "sendMessage"
name of the method that is triggered when the user taps the screen button.
3 Open the Java/com.mycompany.myfirstapp directory under the Myactivity.java file.
4 Add the SendMessage () function in Myactivity.java:
Java/com.mycompany.myfirstapp/myactivity.java
/** Called when the user clicks the Send button */public void sendMessage(View view) { // Do something in response to button}
In order for the system to match the method (the SendMessage method you just added in Myactivity.java) with the android:onClick
method name provided in the attribute, their names must be identical, and it is important to note that this method must meet the following conditions:
- is the public function
- No return value
- Parameter unique (for view type, represents clicked views)
Next, you can write the read text in this method and upload the content to another activity's code.
Build a intent
Intent is an object that provides runtime bindings in different components, such as two activity. On Intent
behalf of an application "want to do something", you can use it for a variety of tasks, but most of the time they are used to start another activity. More detailed information can be found in intents and Intent Filters.
1 Create one in the Myactivity.java sendMessage()
method Intent
and start DisplayMessageActivity
the activity named:
Java/com.mycompany.myfirstapp/myactivity.java
Intent intent = new Intent(this, DisplayMessageActivity.class);
Note: If you are using an IDE like Android studio, the DisplayMessageActivity
reference here will be an error, because the class does not exist, and for the time being ignore this error, we will soon be going to create this class.
There are two parameters in this intent constructor:
The first parameter is the context (the reason it is used this
because the current activity is a Context
subclass)
Accepts the system's class (in this case, the activity that will be started) that sends the intent application component.
Android Studio prompts you to import the intent class.
2 Import the intent class at the beginning of the file:
Java/com.mycompany.myfirstapp/myactivity.java
import android.content.Intent;
Tip: in Android studio, press ALT + Enter to import missing classes (use OPTION + return in Mac)
3 The sendMessage()
edittext element is obtained by using the Findviewbyid () method in the method.
Java/com.mycompany.myfirstapp/myactivity.java
public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message);}
4 Import the EditText class at the beginning of the file.
In Android studio, press ALT + Enter to import the missing class (use OPTION + return in Mac)
5 Associate the text content of the EditText to a local message variable, and use the Putextra () method to pass the value to intent.
Java/com.mycompany.myfirstapp/myactivity.java
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);}
Intent can carry a key-value pair data type called Extras . The PutExtra () method takes the key name as the first argument and the value as the second argument.
6 in MyActivity class, define Extra_message:
Java/com.mycompany.myfirstapp/myactivity.java
public class MyActivity extends ActionBarActivity { public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE"; ...}
To enable the newly launched activity to query the extra data. It is good practice to define a key as a public type constant, usually using the application package name as a prefix, so that the key is unique when the application interacts with other applications.
7 in the SendMessage () function, call StartActivity () to complete the start of the new activity, and now the complete code should look like this:
Java/com.mycompany.myfirstapp/myactivity.java
/** 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);}
To run this method, the system will instantiate the specified in after receiving our request Intent
Activity
, and now we need to create a DisplayMessageActivity
class to enable the program to execute.
Create a second activity
All subclasses of activity must implement the OnCreate () method. This method is called when the instance of the activity is created, and the activity layout must be defined with Setcontentview () to initialize the activity.
Create a new activity using Android Studio
Activity created using Android Studio implements a default OnCreate () method.
In the Java directory of Android Studio, select the package name Com.mycompany.myfirstapp, right-click on New > Activity > Blank activity.
In the Choose Options window, configure the activity:
- Activity Name: displaymessageactivity
- Layout Name: activity_display_message
- Title: My Message
- Hierarchical Parent: com.mycompany.myfirstapp.MyActivity
Package Name:com.mycompany.myfirstapp Click Finish.
3 Open the Displaymessageactivity.java file, this class has implemented the OnCreate () method, and you need to update this method later.
If you are using Android Studio development, you can now click the Send button to start the activity, but the default content provided by the template is "Hello world", which is later modified to show the custom text content.
To create an activity using the command lineIf you use the command-line tool to create an activity, follow these steps:
1 under the src/directory of the project, create a new file Displaymessageactivity.java next to Myactivity.java.
2 Write the following code:
public class Displaymessageactivity extends appcompatactivity {@Override protected void onCreate (Bundle Savedinstan Cestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_display_message); if (savedinstancestate = = null) {Getsupportfragmentmanager (). BeginTransaction (). Add (R.id.conta Iner, New Placeholderfragment ()). commit (); }} @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a paren T activity in Androidmanifest.xml. int id = item.getitemid (); if (id = = r.id.action_settings) {return true; } return super.onoptionsitemselected (item); }/** * A placeholder fragment containing a simple view. */public static class Placeholderfragment extends Fragment {public PLaceholderfragment () {} @Override public View oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View Rootview = inflater.inflate (r.layout.fragment_display_messag E, container, false); return rootview; } }}
Note: If you are using an IDE other than Android Studio, the project may not contain the setContentView()
requested activity_display_message
layout, but that's OK, because the method will be modified.
3 Add the title of the new activity to the Strings.xml file:
<resources> ... <string name="title_activity_display_message">My Message</string></resources>
4 Label the displaymessageactivity in the Androidmanifest.xml application tag as follows:
<application ... > ... <activity android:name="com.mycompany.myfirstapp.DisplayMessageActivity" android:label="@string/title_activity_display_message" android:parentActivityName="com.mycompany.myfirstapp.MyActivity" > <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.mycompany.myfirstapp.MyActivity" /> </activity></application>
android:parentActivityName
Property declares the name of the parent activity at the activity logic level in the application. This value is used by the system to implement the default navigation actions, such as up navigation in Android 4.1 (API level 16) or later. Using the support Library, the elements shown above <meta-data>
can provide the same functionality for older versions of Android.
Note: Our Android SDK should already contain the latest Android support Library, which is included in the ADT plugin. However, if you are using a different IDE, you will need to install it in Adding platforms and Packages. When using templates in Android Studio, the support library is automatically added to our project (in Android dependencies you see the corresponding JAR file). If you do not use Android Studio, you will need to manually add the support library to our project, referring to the setting up's support library.
Receive IntentEach activity is invoked through intent, regardless of where the user navigates. We can get the intent that initiates the activity and the data it contains by calling Getintent ().
1 Edit the Displaymessageactivity.java file under the Java/com.mycompany.myfirstapp directory.
2 Get intent and assign to local variables.
Intent intent = getIntent();
3 Import the package for intent.
In Android studio, press ALT + Enter to import the missing class (use OPTION + return in Mac).
4 Call Getstringextra () to extract the message passed from MyActivity.
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
Display text1 in the Res/layout directory, edit the file content_display_message.xml
.
2 Add the id attribute to the tag, and you will need to call the object with this id attribute later.
< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"...android:id="@+id/content"></RelativeLayout>
3 Re-editDisplayMessageActivity.java
4 onCreate()
creating an object in a methodTextView
TextView textView = new TextView(this);
5 use setText()
to set the text font size and content.
textView.setTextSize(40);textView.setText(message);
6 will be TextView
added to the previously R.id.content
marked RelativeLayout
RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);layout.addView(textView);
7 Import the package for TextView.
In Android studio, press ALT + Enter to import the missing class (use OPTION + return in Mac).
The complete OnCreate () method for displaymessageactivity should be as follows:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_display_message); Toolbar Toolbar = (Toolbar) Findviewbyid (R.id.toolbar); Setsupportactionbar (toolbar); Floatingactionbutton fab = (Floatingactionbutton) Findviewbyid (R.id.fab); Fab.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {Snack Bar.make (View, "Replace with your own action", Snackbar.length_long). Setaction ("action", NULL) . Show (); } }); Getsupportactionbar (). Setdisplayhomeasupenabled (True); Intent Intent = Getintent (); String message = Intent.getstringextra (myactivity.extra_message); TextView TextView = new TextView (this); Textview.settextsize (40); Textview.settext (message); Relativelayout layout = (relativelayout) Findviewbyid (r.id.content); Layout.addview (TextView);}
Now you can run the app, enter the information in the text, click the Send button, OK, now you can see the message sent over the second activity.
So far, we've created our first Android app!
4) 10 minutes Learn android--set up the first app and start another activity