Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
67 views
in Technique[技术] by (71.8m points)

Use onactivityresult android

I want to call a method from mainactivity in other activities. For that, I've researched a lot and found that using OnActivityResult is the best option. Can anyone please explain how to use this method with the help of an example? I've gone through similar questions but found them confusing. Thanks!

EDIT:I have a custom dialog activity in my app. It asks the users whether they want to start a new game or not and it has two buttons yes and no. I want to implement the above method only to get the pressed button.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Define constant

public static final int REQUEST_CODE = 1;

Call your custom dialog activity using intent

Intent intent = new Intent(Activity.this,
                    CustomDialogActivity.class);
            startActivityForResult(intent , REQUEST_CODE);

Now use onActivityResult to retrieve the result

@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();
        }

    }

In custom dialog activity use this code to set result

Intent intent = getIntent();
intent.putExtra("key", value);
setResult(RESULT_OK, intent);
finish();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...