建立一个MainActivity:
public class MainActivity extends Activity { private TextView tv2; private Button btn1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv2=(TextView) findViewById(R.id.tv2); btn1=(Button) findViewById(R.id.btn1); btn1.setOnClickListener(getListener()); } private OnClickListener getListener() { OnClickListener onlis=new OnClickListener(){ @Override public void onClick(View arg0) { Intent intent=new Intent(MainActivity.this,NextActivity.class); startActivityForResult(intent, 1000); } }; return onlis; } /* * 接受下一个页面返回的结果 * (non-Javadoc) * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode==1000 && resultCode==1001){ tv2.setText(data.getStringExtra("return")); } super.onActivityResult(requestCode, resultCode, data); } }当使用Activity回传值时,需要在启动下一个Activity时,调用startActivityForResult(intent,requestCode)方法,其中的requestCode可以自己设定int类型值,也可以用android本身提供的值;要获取下一个activity的回传值,调用onActivityResult(int requestCode, int resultCode, Intent data),即可回去回掉值;
建立第二个NextActivity
public class NextActivity extends Activity { private EditText et; private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_next); et=(EditText) findViewById(R.id.et); btn=(Button) findViewById(R.id.btn); btn.setOnClickListener(getLis()); } private OnClickListener getLis() { OnClickListener lis=new OnClickListener(){ @Override public void onClick(View arg0) { String etString=et.getText()!=null?et.getText().toString().trim():""; Intent intent=new Intent(); intent.putExtra("return", etString); setResult(1001, intent); finish(); } }; return lis; } }
在第二个activity中需要设置一个空的Intent,绑定需要回传的值,调用setResult(resultCode,intent),其中resultCode可以自由设定也可以用android自带的int类型值,然后finis当前页面,即可将该值回掉到上一个页面。
略去上述两个对应的layout
<p>版权声明:本文为博主原创文章,未经博主允许不得转载。</p>