startActivityForResult()在使用過(guò)程中,還需要與onActivityResult()配對(duì)使用,定義大量的requestCode,屬實(shí)比較麻煩,而現(xiàn)在startActivityForResult()方法已經(jīng)被谷歌標(biāo)記為了Deprecated,方法不推薦使用了,谷歌推薦使用Activity Results API。 首先引入:
implementation 'androidx.activity:activity:1.2.0-beta01'
implementation 'androidx.fragment:fragment:1.3.0-beta01'
第一個(gè)activity代碼:
public class MainActivity extends AppCompatActivity {
ActivityResultLauncher launcher = registerForActivityResult(new ResultContract(), new ActivityResultCallback<String>() {
@Override
public void onActivityResult(String result) {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.tv_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launcher.launch(true);
}
});
}
class ResultContract extends ActivityResultContract<Boolean, String> {
@NonNull
@Override
public Intent createIntent(@NonNull Context context, Boolean input) {
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
intent.putExtra("b", input);
return intent;
}
@Override
public String parseResult(int resultCode, @Nullable Intent intent) {
return intent.getStringExtra("s");
}
}
}
- 自定義Contract繼承自ActivityResultContract,有兩個(gè)參數(shù)類(lèi)型,一個(gè)是傳遞類(lèi)型,另一個(gè)是返回類(lèi)型。在createIntent()中構(gòu)造Intent ,在parseResult()中從intent解析返回參數(shù)。
- registerForActivityResult()注冊(cè)Contract,并處理返回參數(shù)業(yè)務(wù)邏輯。
注意這里,如果不在聲明ActivityResultLauncher時(shí)注冊(cè),會(huì)報(bào)錯(cuò):
Caused by: java.lang.IllegalStateException: LifecycleOwner com.example.test2.MainActivity@5a3abbd is attempting to register while current state is STARTED. LifecycleOwners must call register before they are STARTED.
- launcher.launch()執(zhí)行,傳入?yún)?shù)。
第二個(gè)activity代碼和以前方式一樣:
public class MainActivity2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
findViewById(R.id.tv_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_OK, new Intent().putExtra("s", "哈哈哈"));
finish();
}
});
}
}
以上就是一個(gè)簡(jiǎn)單的完整使用過(guò)程。
參考:再見(jiàn)!onActivityResult!你好,Activity Results API!
|