Getting Started - Starting Another Activity

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 the View 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 the Activity class is a subclass of Contex)

  • The Class of the app component to which the system should deliver the Intent (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);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章