首先要创建2个activity 分别为MainActivity和OneActiivity
MainActivity代码如下:
package com.tp.soft.app; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener{ private Button mTzBtn; private TextView mShow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTzBtn = (Button) findViewById(R.id.tzBtn); mTzBtn.setOnClickListener(this); mShow = (TextView) findViewById(R.id.showMsg); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == 1){ String msg = data.getStringExtra("FromOneActivity"); mShow.setText(msg); } } @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, OneActivity.class); String content = "Hello,OneActivity"; intent.putExtra("FromMainActivity", content); startActivityForResult(intent, 1); } }
其中调用
startActivityForResult(intent, 1);中的1就是
onActivityResult返回的requestCode。
OneActivity代码如下:
package com.tp.soft.app; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class OneActivity extends Activity implements OnClickListener { private Button mbackBtn; private TextView mShow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_one); mbackBtn = (Button) findViewById(R.id.backBtn); mbackBtn.setOnClickListener(this); mShow = (TextView) findViewById(R.id.showTxt); Intent intent = getIntent(); String show = intent.getStringExtra("FromMainActivity"); mShow.setText(show); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.one, menu); return true; } @Override public void onClick(View v) { Intent intent = new Intent(OneActivity.this, MainActivity.class); intent.putExtra("FromOneActivity", "Hello,MainActivity"); setResult(RESULT_OK, intent); finish(); } }