MainActivity包含一个EditText和一个Button,DisplayMessageActivity包含一个TextView,这个TextView的内容是EditText传过来的。
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editText = (EditText)findViewById(R.id.editText);
String message = editText.getText().toString();
Intent intent = DisplayMessageActivity.newIntent(MainActivity.this,message);
startActivity(intent);
}
});
}
}
DisplayMessageActivity.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.exampe.administrator.intentdemo.message";
public static Intent newIntent( Context context,String message){
Intent intent = new Intent(context,DisplayMessageActivity.class);
intent.putExtra(EXTRA_MESSAGE,message);
return intent;
}
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
textView =(TextView)findViewById(R.id.textView);
String message = getIntent().getStringExtra(EXTRA_MESSAGE);
textView.setText(message);
}
}
最终效果: