Android利用startActivityForResult返回數據到前一個Activity
在Android里面,從一個Activity跳轉到另一個Activity、再返回,前一個Activity默認是能夠保存數據和狀態的。但這次我想通過利用startActivityForResult達到相同的目的,雖然看起來變復雜了,但可以探索下startActivityForResult背后的原理和使用注意事項。
要實現的功能如下:從Activity A將數據傳到Activity B,再從Activity B中獲取數據后,再傳回Activity A。在Activity B中添加一個“回到上一頁”的Button,返回到Activity A之后,需要保留之前輸入的相關信息,我們用startActivityForResult來拉起Activity B,這樣,Activity A就會有一個等待Activity B的返回。
具體步驟如下: 在Activity A中有一個Button,點擊Button后,獲取要傳到Activity B的數據,將數據封裝到Bundle中,再調用startActivityForResult將數據傳到Activity B Activity A 重寫onActivityResult函數,判斷requestCode和resultCode是否是我們預期的結果,如果是,那么從Bundle中獲取數據,重新顯示在Activity A中 在Activity B中獲取Activity A傳過去的Intent對象,并取出Bundle對象,再從Bundle中取出數據字段,顯示在當前頁面 Activity B中也有一個Button,點擊Button后,調用setResult傳回結果,并關閉當前頁面。因此,看起來的效果就是回到了Activity A 源碼如下:1、Activity A的實現:
public class ExampleActivity extends Activity { private EditText mEditText; private RadioButton mRb1; private RadioButton mRb2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_page_layout); Button button = findViewById(R.id.buttonGoToLayout2); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mEditText = findViewById(R.id.editText); // 獲取輸入的身高 double height = Double.parseDouble(mEditText.getText().toString()); // 獲取性別 String gender = ''; mRb1 = findViewById(R.id.radioButtonMale); mRb2 = findViewById(R.id.radioButtonFemale); if (mRb1.isChecked()) { gender = 'M'; } else { gender = 'F'; } Intent intent = new Intent(ExampleActivity.this, SecondActivity.class); // 將數據傳入第二個Activity Bundle bundle = new Bundle(); bundle.putDouble('height', height); bundle.putString('gender', gender); intent.putExtras(bundle); startActivityForResult(intent, 0); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == 0) { Bundle bundle = data.getExtras(); double height = bundle.getDouble('height'); String gender = bundle.getString('gender'); mEditText.setText('' + height); if (gender.equals('M')) { mRb1.setChecked(true); } else { mRb2.setChecked(true); } } }}
2、布局文件main_page_layout.xml:
<RelativeLayout xmlns:android='http://schemas.android.com/apk/res/android' android:layout_width='match_parent' android:layout_height='match_parent' android:layout_gravity='center'> <TextView android: android:layout_width='match_parent' android:layout_height='wrap_content' android:text='計算標準體重' android:paddingTop='20dp' android:paddingLeft='20dp' android:textSize='30sp'/> <TextView android:text='性別:' android:layout_width='wrap_content' android:layout_height='wrap_content' android: android:layout_alignStart='@id/textView1' android:layout_marginTop='38dp' android:layout_below='@id/textView1' android:layout_marginStart='46dp'/> <TextView android:text='身高:' android:layout_width='wrap_content' android:layout_height='wrap_content' android: android:layout_alignStart='@id/textView1' android:layout_marginStart='46dp' android:layout_below='@id/textView3' android:layout_marginTop='29dp'/> <EditText android:layout_width='wrap_content' android:layout_height='wrap_content' android: android:layout_toEndOf='@id/textView4' android:layout_marginStart='36dp' android:autofillHints='@string/app_name' android:hint='0' android:layout_alignBaseline='@id/textView4'/> <TextView android:layout_width='wrap_content' android:layout_height='wrap_content' android:text='厘米' android:layout_alignBaseline='@id/editText' android:layout_toRightOf='@id/editText' android:layout_marginStart='10dp' /> <RadioButton android:layout_below='@id/textView1' android: android:text='男' android:layout_width='wrap_content' android:layout_height='wrap_content' android:layout_alignStart='@id/textView1' android:layout_marginTop='30dp' android:layout_marginStart='113dp'/> <RadioButton android: android:text='女' android:layout_width='wrap_content' android:layout_height='wrap_content' android:layout_below='@id/textView1' android:layout_toEndOf='@id/radioButtonMale' android:layout_marginLeft='15dp' android:layout_marginTop='30dp' android:layout_marginStart='49dp'/> <Button android:text='計算' android:layout_width='wrap_content' android:layout_height='wrap_content' android: android:layout_marginTop='90dp' android:layout_below='@id/radioButtonMale' android:layout_alignStart='@id/textView1' android:layout_marginStart='92dp'/></RelativeLayout>
3、Activity B的實現:
public class SecondActivity extends Activity { private Intent mIntent; private Bundle mBundle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_layout); mIntent = getIntent(); mBundle = mIntent.getExtras(); // 記得判空 if (mBundle == null) { return; } // 獲取Bundle中的數據 double height = mBundle.getDouble('height'); String gender = mBundle.getString('gender'); // 判斷性別 String genderText = ''; if (gender.equals('M')) { genderText = '男性'; } else { genderText = '女性'; } // 獲取標準體重 String weight = getWeight(gender, height); // 設置需要顯示的文字內容 TextView textView = findViewById(R.id.textView2); textView.setText('你是一位' + genderText + 'n你的身高是' + height + '厘米n你的標準體重是' + weight + '公斤'); Button button = findViewById(R.id.buttonGoBack); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 設置結果,并關閉頁面 setResult(RESULT_OK, mIntent); finish(); } }); } // 四舍五入格式化 private String format(double num) { NumberFormat formatter = new DecimalFormat('0.00'); return formatter.format(num); } // 計算標準體重的方法 private String getWeight(String gender, double height) { String weight = ''; if (gender.equals('M')) { weight = format((height - 80) * 0.7); } else { weight = format((height - 70) * 0.6); } return weight; }}
4、Activity B的布局:
<RelativeLayout xmlns:android='http://schemas.android.com/apk/res/android' android:layout_width='match_parent' android:layout_height='match_parent'> <TextView android:text='This is the second layout' android:layout_width='wrap_content' android:layout_height='wrap_content' android: android:paddingTop='30dp' android:paddingStart='50dp'/> <Button android:layout_width='wrap_content' android:layout_height='wrap_content' android: android:text='回到上一頁' android:layout_alignStart='@id/textView2' android:layout_below='@id/textView2' android:layout_marginTop='54dp' android:layout_marginStart='52dp'/></RelativeLayout>不過這里有3個地方需要注意:
1.startActivityForResult的第二個參數requestCode傳的是0,那么我們分別看下傳遞的值小于0和大于0是什么結果:(1)傳一個小于0的值,比如-1:等同于調用 startActivity,onActivityResult不會被調用(2)傳一個大于0的值,比如1:效果等同于傳0,onActivityResult的第一個參數正是我們通過startActivityForResult傳遞的requestCode
2.onActivityResult的第二個參數resultCode:它是第二個activity通過setResult返回的,常用的取值有2個:RESULT_CANCELED、RESULT_OK(1)RESULT_CANCELED:Activity B拉起失敗,比如crash(2)RESULT_OK:Activity B操作成功后的返回值
還有一個不太常用的取值:RESULT_FIRST_USER,Android源碼對這個取值的定義是“user-defined activity results”(用戶自定義的),我在源碼中全局搜索了下,用的地方不多,挑了一兩個使用的地方:
(1)PackageInstaller下面的InstallFailed.java(安裝apk失敗的相關頁面)
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); int statusCode = getIntent().getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE); if (getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) { // …….. setResult(Activity.RESULT_FIRST_USER, result); finish(); }
(2)PackageInstaller下面的InstallStaging.java
private void showError() { (new ErrorDialog()).showAllowingStateLoss(getFragmentManager(), 'error'); // ……. setResult(RESULT_FIRST_USER, result);}
PackageInstaller下面的UninstallerActivity.java(卸載apk的相關頁面):在onCreate方法里面有多處設置為RESULT_FIRST_USER。因此,我的理解是業務自身在一些錯誤或無效的場景下使用,由業務自己定義。
3. 如果啟動Activity B時設置了new_task啟動模式,進入Activity B后,Activity A會立即回調onActivityResult,而且resultCode是0;從Activity B setResult返回后,不再有onActivityResult的回調!
以上就是Android利用startActivityForResult返回數據到前一個Activity的詳細內容,更多關于Android 返回數據到前一個Activity的資料請關注好吧啦網其它相關文章!
相關文章: