当前位置:   article > 正文

onBackPressed() 使用

onbackpressed

onBackPressed() : 当手机按下back键时,执行此方法。

 

用此方法时 :有super.onBackPressed() 时 不能把在此方法中设置的 intent 传回上一个Activity ,

                        因此 去掉super.onBackPressed()  在末尾加上finish();

                        在上一个activity中用onActivityResult() 方法接受上此Activity的onBackPressed()方法传回去的intent,

                         在onBackPressed()设置resultCode  在上一个Activity 的OnActivityResult()中验证;

  1. package com.orient;
  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. import android.widget.TextView;
  9. public class TestProjectActivity extends Activity {
  10. String result;
  11. TextView view;
  12. @Override
  13. public void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.main);
  16. view = (TextView) findViewById(R.id.text);
  17. Button back = (Button) findViewById(R.id.button);
  18. back.setOnClickListener(new OnClickListener() {
  19. @Override
  20. public void onClick(View v) {
  21. Intent intent = new Intent(TestProjectActivity.this,
  22. CopyOfTestProjectActivity.class);
  23. startActivityForResult(intent, 1111);
  24. }
  25. });
  26. }
  27. @Override
  28. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  29. super.onActivityResult(requestCode, resultCode, data);
  30. if (requestCode == 1111 && resultCode == 111 && data != null) {
  31. result = data.getStringExtra("activity2");
  32. view.setText(result);
  33. }
  34. }
  35. }

传值Activity:
  1. package com.orient;
  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.util.Log;
  6. import android.view.View;
  7. import android.view.View.OnClickListener;
  8. import android.widget.Button;
  9. public class CopyOfTestProjectActivity extends Activity {
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.main2);
  14. Log.v("Test21", "Display onBackPressed");
  15. }
  16. @Override
  17. public void onBackPressed() {
  18. Intent intent=new Intent();
  19. intent.putExtra("activity2", "TestText");
  20. setResult(111, intent);
  21. finish();
  22. }
  23. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/531639
推荐阅读
相关标签
  

闽ICP备14008679号