http://developer.android.com/training/basics/firstapp/starting-activity.html
1, Compared with setClickListener in activity, another way to set onClick to a button in XML file:
add theandroid:onClick="sendMessage"
attribute to the <Button>
element.
"sendMessage" is a method in the activity that the system calls when the user click the button.
2, in activity,
publicvoid sendMessage(View view){
// Do something in response to button
}
the sendMessage method must:
Be public
Have a void return value
Have a
View
as the only parameter (this will be theView
that was clicked)
3,
Intent intent =newIntent(this,DisplayMessageActivity.class);
The constructor used here takes two parameters:
A
Context
as its first parameter (this
is used because theActivity
class is a subclass ofContex
)The
Class
of the app component to which the system should deliver theIntent
(in this case, the activity that should be started)
4, add the content of EditText to intent
Intent intent =newIntent(this,DisplayMessageActivity.class);
EditText editText =(EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
The putExtra()
method takes the key name in the first parameter and the value in the second parameter.
5, get intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
6, display the message
TextView textView =newTextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
转载于:https://blog.51cto.com/succi/1343854