startActivityForResult()废弃/过时后,我们可以用registerForActivityResult()替代。
代码如下:
FirstAvitvity.class
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityResultLauncher launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if(resultresult.getResultCode() == Activity.RESULT_OK){
Log.d("TAG", result.getData().getStringExtra("data_return"));
}
}
});
Button button1 = (Button) findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
launcher.launch(intent);//启动intent跳转
}
});
}
}
SecondActivity
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button button2 = (Button) findViewById(R.id.button_2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.putExtra("data_return","Hello World!");
setResult(RESULT_OK,intent);
finish();
}
});
}
}
Kotlin写法如下
FirstAvitvity.class
class FirstActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK && result.data != null) {
result.data?.getStringExtra("data_return")?.let {
Log.e("TAG", it)
}
}
}
findViewById<Button>(R.id.button_1).setOnClickListener {
val intent = Intent(this, SecondAct::class.java)
launcher.launch(intent)
}
}
}
SecondActivity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
findViewById<Button>(R.id.button_2).setOnClickListener {
val intent = Intent()
intent.putExtra("data_return","Hello World!")
setResult(RESULT_OK,intent)
finish()
}
}
}