赞
踩
onBackPressed() : 当手机按下back键时,执行此方法。
用此方法时 :有super.onBackPressed() 时 不能把在此方法中设置的 intent 传回上一个Activity ,
因此 去掉super.onBackPressed() 在末尾加上finish();
在上一个activity中用onActivityResult() 方法接受上此Activity的onBackPressed()方法传回去的intent,
在onBackPressed()设置resultCode 在上一个Activity 的OnActivityResult()中验证;
- package com.orient;
-
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class TestProjectActivity extends Activity {
- String result;
- TextView view;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- view = (TextView) findViewById(R.id.text);
-
- Button back = (Button) findViewById(R.id.button);
- back.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View v) {
-
- Intent intent = new Intent(TestProjectActivity.this,
- CopyOfTestProjectActivity.class);
- startActivityForResult(intent, 1111);
- }
- });
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (requestCode == 1111 && resultCode == 111 && data != null) {
- result = data.getStringExtra("activity2");
- view.setText(result);
- }
- }
- }
- package com.orient;
-
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
-
- public class CopyOfTestProjectActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main2);
-
- Log.v("Test21", "Display onBackPressed");
- }
-
- @Override
- public void onBackPressed() {
- Intent intent=new Intent();
- intent.putExtra("activity2", "TestText");
- setResult(111, intent);
- finish();
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。