android学习笔记 Activity Result API 例程

Posted before16

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android学习笔记 Activity Result API 例程相关的知识,希望对你有一定的参考价值。

使用默认contract类 StartActivityForResult

MainActivity 代码

public class MainActivity extends AppCompatActivity {
    //You need to registerForActivityResult before onStart of the Activity.
    ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Toast.makeText(MainActivity.this, result.getData().getStringExtra("result"), Toast.LENGTH_SHORT).show();
                    }
                }
            });
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                intent.putExtra("post", "123");
                mStartForResult.launch(intent);
            }
        });
    }
}

MainActivity2代码

public class MainActivity2 extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toast.makeText(this,getIntent().getStringExtra("post"), Toast.LENGTH_SHORT).show();
        findViewById(R.id.button_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_OK, new Intent().putExtra("result", "哈哈哈"));
                finish();
            }
        });
    }
}

自定义contract类

 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("post", input);
            return intent;
        }

        @Override
        public String parseResult(int resultCode, @Nullable Intent intent) {
            return intent.getStringExtra("result");
        }
    }

以上是关于android学习笔记 Activity Result API 例程的主要内容,如果未能解决你的问题,请参考以下文章

android学习笔记28——Activity生命周期

Android学习笔记(44):Activity

Android学习笔记——Activity之间传递参数

Android学习笔记 Activity的生命周期

android activity声明周期学习笔记

学习笔记Android中的Activity启动模式