In this section, I'll start another Activity when I click the the Send button in Main Activity.
Let's see the following.
1. Respond to the Send Button.
==== activity_main.xml ====
<LinearLayout 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:orientation="horizontal" > <EditText android:id="@+id/message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="Enter a message" android:layout_weight="1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" android:textSize="20sp" android:onClick="sendMessage" /> </LinearLayout>
: the android:onClick attribute's value, "sendMessage" is the name of a method in MainActivity that the system calls when the user click the button.
2. Build an Intent
==== MainActivity.java ====
public void sendMessage(View view) { Intent intent = new Intent(getBaseContext(), DisplayMessageActivity.class); editText = (EditText)findViewById(R.id.message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent);
}
- Add the corresponding method in the MainActivity.
- Inside the sendMessage method, create an Intent to start an activity called DisplaymessageActivity.
3. Create the second Activity
==== DisplayMessageActivity.java ====
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Get the message from the Intent Intent intent = getIntent(); String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); TextView textView = new TextView(this); textView.setTextSize(40); textView.setText(message); // Set the Textview as an activity layout setContentView(textView); }
- We can now run the app.
- When it opens, type a message in the textfield, click the button, and the message in the textfield appears on the second activity.
'Android > Activity' 카테고리의 다른 글
Action Bar: Adding Action Buttons (0) | 2014.02.03 |
---|