内容纲要
目的
将向 MainActivity 添加一些代码,以便在用户点按 Send 时,启动一个新的 Activity 来显示消息
过程
添加调用方法
/** Called when the user taps the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
创建Intent意图
Intent是在相互独立的组件(如两个 Activity)之间提供运行时绑定功能的对象。
Intent 表示某个应用“执行某项操作的意图
”。您可以使用 Intent 来执行多种任务,但在本课中,您的 Intent 将用于启动另一个 Activity。
public void sendMessage(View view) {
Intent intent = new Intent(this,secondary.class);
TextView tvFirst = findViewById(R.id.tvFirst);
String message_tvFirst = tvFirst.getText().toString();
intent.putExtra("myInfo",message_tvFirst);
startActivity(intent);
}
添加另一个Activity
App > New > Activity > Empty Activity
接收意图
public void receiveIntent() {
Intent reIntent = getIntent();
String message = reIntent.getStringExtra("myInfo");
TextView tvInfo = findViewById(R.id.tvInfo);
tvInfo.setText(message);
}
添加向上导航功能(返回)
在 AndroidManifest.xml
文件中声明哪个 Activity 是逻辑父屏幕
<activity android:name=".secondary" android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>