Android startActivityForResult()代替方案示例
目录
- startActivityForResult()方法废弃
- 目前的代替方案案例
- 从A跳到B,A页面逻辑
- 从A跳到B,B页面回退逻辑
startActivityForResult()方法废弃
安卓项目compileSdk为32,在使用startActivityForResult()方法时发现android studio提示此方法已经废弃了。
目前的代替方案案例
// 确保 app 的 build.gradle中已经引入了androidx.appcompat:appcompat dependencies { implementation 'androidx.appcompat:appcompat:1.4.1' // 确定 }
从A跳到B,A页面逻辑
package com.example.test1; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.example.test1.ui.login.LoginActivity; // B页面例子 import com.google.android.material.snackbar.Snackbar; public class MainActivity extends AppCompatActivity implements View.OnClxqzHJOsKXGickListener { private static StxqzHJOsKXGring TAG = "MainActivity"; private ActivityResultLauncher<Intent> register; @SuppressLint("ResourceAsColor") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.my_button).setOnClickListener(this); register = registerForActivityResujavascriptlt(new ActivityResultContracts.StartActivityForResult(), newjavascript ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { Log.i(TAG, "onActivityResuljst: _____" + result); if (result != null) { Intent intent = result.getData(); if (intent != null && result.getResultCode() == Activity.RESULT_OK) { Bundle myBundle = intent.getExtras(); String my_name = myBundle.getString("my_name"); String my_sex = myBundle.getString("my_sex"); // 下一个Activity回退后 在此获取返回的值 Log.i(TAG, "onCreate: 获取返回传值my_name__________" + my_name); // ___获取返回传值my_namezhangsan000 Log.i(TAG, "onCreate: 获取返回传值my_sex__________" + my_sex); // ___获取返回传值my_sex男 } } } }); } @Override public void onClick(View view) { if (view.getId() == R.id.my_button) { Intent intent = new Intent(this, LoginActivity.class); // 用register.launch跳转至B register.launch(intent); } } }
从A跳到B,B页面回退逻辑
// B页面的后退逻辑 public void myBack(View view) { Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("my_name", "zhangsan000"); bundle.putString("my_sex", "男"); intent.putExtras(bundle); // 携带意图返回上一个页面 RESULT_OK代表处理成功了 setResult(Activity.RESULT_OK, intent); // 结束当前页面 finish(); };
以上就是Android startActivityForResult()代替方案示例的详细内容,更多关于Android startActivityForResult()的资料请关注编程客栈(www.devze.com)其它相关文章!
精彩评论