Starting Another Activity

为简单起见,此处只保留了关键代码。详细过程参见官方教程:Starting Another Activity

在MainActivity类中,我们有如下代码:

public final static String EXTRA_MESSAGE = "com.example.simon.myapplication.MESSAGE";
/** 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);
}

 注:1) sendMessage为MainActivity中按钮Send Button的响应函数,即当按钮被按下时执行该函数。

        2) Intent原型为:Intent(Context, Class),指定启动DisplayMessageActivity对应的Activity。

        3) 调用startActivity启动新的Acitvity。

在DisplayMessageActivity中,有如下代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MyActivity.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);
}

注:1) 函数getIntent()返回启动该Acitvity的Intent。

总结:1) 在MainAcitivity中,调用startActivity函数来启动Intent中指定的Activity。

          2) 在DisplayMessageActivity中,使用getIntent函数获取该Intent对象。

原文地址:https://www.cnblogs.com/moderate-fish/p/4263287.html