intent作为我们4大组件之一,消息的传递的重要途径,今天我们就来看看intent是如何实现消息的回传的
package com.example.jumpforresult; import android.os.Bundle; import android.app.Activity; import android.app.Instrumentation.ActivityResult; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity implements OnClickListener{ public static final int frequestCode=111; EditText et; Button bt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et=(EditText) findViewById(R.id.et); bt = (Button) findViewById(R.id.but); bt.setOnClickListener(this); } @Override public void onClick(View view) { // TODO Auto-generated method stub String msg=et.getText().toString(); Intent intent=new Intent(this,SecActivity.class); intent.putExtra("akey", msg); startActivity(intent); startActivityForResult(intent, frequestCode); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //这个方法是我们需要获得消息而重写的一个方法 // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); //判断是否是我们需要的带回来那个activity if(requestCode==frequestCode){ if(resultCode==Activity.RESULT_OK){ //获取数据 String value=data.getStringExtra("key"); bt.setText(value); } } } }
package com.example.jumpforresult; import android.os.Bundle; import android.app.Activity; import android.app.Instrumentation.ActivityResult; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity implements OnClickListener{ public static final int frequestCode=111; EditText et; Button bt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et=(EditText) findViewById(R.id.et); bt = (Button) findViewById(R.id.but); bt.setOnClickListener(this); } @Override public void onClick(View view) { // TODO Auto-generated method stub String msg=et.getText().toString(); Intent intent=new Intent(this,SecActivity.class); intent.putExtra("akey", msg); startActivity(intent); startActivityForResult(intent, frequestCode); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //这个方法是我们需要获得消息而重写的一个方法 // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); //判断是否是我们需要的带回来那个activity if(requestCode==frequestCode){ if(resultCode==Activity.RESULT_OK){ //获取数据 String value=data.getStringExtra("key"); bt.setText(value); } } } }