onActivityResult 方法调用onbutton点击

Pra*_*eep 5 android

在此输入图像描述请写下如何在按钮单击时调用片段的 onActivityResult 的答案

在此输入图像描述

 Button button=view.findViewById(R.id.bbbtttnnn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.putExtra("name","charan");
                startActivityForResult(intent,45);
            }
        });
Run Code Online (Sandbox Code Playgroud)

小智 0

定义常数

public static final int REQUEST_CODE = 1;
Run Code Online (Sandbox Code Playgroud)

使用意图

Intent intent = new Intent(Activity.this,
                    XYZActivity.class);
            startActivityForResult(intent , REQUEST_CODE);
Run Code Online (Sandbox Code Playgroud)

现在使用 onActivityResult 检索结果

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == REQUEST_CODE  && resultCode  == RESULT_OK) {

                String requiredValue = data.getStringExtra("key");
            }
        } catch (Exception ex) {
            Toast.makeText(Activity.this, ex.toString(),
                    Toast.LENGTH_SHORT).show();
        }

    }
Run Code Online (Sandbox Code Playgroud)

在下一个屏幕中使用此代码设置结果

Intent intent = getIntent();
intent.putExtra("key", value);
setResult(RESULT_OK, intent);
finish();
Run Code Online (Sandbox Code Playgroud)