如何使用StartActivityForResult() [英] How to use StartActivityForResult()

查看:54
本文介绍了如何使用StartActivityForResult()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我需要向用户询问快速 input.

我需要从中获取结果 Flash-Activity ,然后返回到上一个.

我已经阅读过StartActivityForResult()方法,但是我不确定如何正确使用它,是否有示例?

我尝试使用在应用于StartActivityForResult()的此方法的所有应用程序中使用的方法,通过意图(作为结果)传递Player对象:

在第二个活动中(我需要从中获得结果的那个活动):

Intent intent = new Intent();
Player playerKilled = players.get(position);

Bundle bundle = new Bundle();
bundle.putSerializable("PLAYER_KILLED", (Serializable) playerKilled);
intent.putExtras(bundle);

setResult(Activity.RESULT_OK, intent);
finish();

我需要记录结果的主要活动:

if (resultCode == Activity.RESULT_OK) {

    Intent intent = this.getIntent();
    Bundle bundle = intent.getExtras();
    playerKilled = (Player)bundle.getSerializable("PLAYER_KILLED");

    Toast.makeText(this, playerKilled.getName() + "the " + playerKilled.getCardName() + " has died, and he/she had the ID: " + playerKilled.getId(), Toast.LENGTH_SHORT).show();

解决方案

您可以通过多种方式请求用户输入,但是,正如您提到的,如果要使用新的Activity,我们可以使用startActivityForResult()启动新活动并从那里返回输入.

首先,我强烈建议您阅读此堆栈溢出答案有关如何使用startActivityForResult()的信息.我将解释如何针对您的特定用例实现它.

因此,您需要了解startActivityForResult()具有两个参数:

  • Intent(用于在活动之间传递数据)
  • 标识您请求的请求代码"整数

优良作法是在两个活动中都可以使用常量作为请求代码.例如,在您的主要活动中,您可以添加:

public static final int REQUEST_CODE = 1;

由于它是public,因此在两个活动中都可以访问,并且由于它是int(整数),因此可以用于请求代码.

在主要活动中,您需要执行一项操作(例如,按下按钮)才能开始第二个活动.假设是单击按钮触发了此操作:

Button button = (Button) findViewById(R.id.your_button);
button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // actions that will happen when the button is pressed:

        Intent intent = new Intent(this, SecondActivity.class);
        startActivityForResult(intent, REQUEST_CODE);
    }
});

基本上,我们正在创建一个Intent,它指定了我们当前的活动(this)和第二个活动.我们将startActivityForResult()方法中的意图与我们先前声明的REQUEST_CODE一起使用.

现在,在第二个活动中,我们需要一些东西来触发数据返回.从您之前提出的问题中,我假设您是希望在单击RecyclerView项目后将数据返回到主活动.这是我对该问题的回答的部分,以显示如何将数据发送回去.

ExampleClickAdapter clickAdapter = new ExampleClickAdapter(yourObjects);
clickAdapter.setOnEntryClickListener(new ExampleClickAdapter.OnEntryClickListener() {
    @Override
    public void onEntryClick(View view, int position) {
        Intent intent = new Intent();
        intent.putExtra("pos", position);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
});
recyclerView.setAdapter(clickAdapter);

上面的内容将从单击的RecyclerView中发回列表项的位置.

看看IntentputExtra()方法.这就是传递数据的方式.您可以看到我在此方法中传递了字符串"pos"和项目position的变量,但是为什么:

intent.putExtra("key", object);

IntentputExtra方法始终使用String键和另一个对象,例如整数变量position.检索该对象时,将再次使用该键(如我稍后将向您展示的那样).

我们使用Activity.RESULT_OK来表示我们正在传递结果,但是如果您不想发送回结果,则可以使用Activity.RESULT_CANCELED-这在我开头提到的答案链接中得到了解释.请注意,如果您使用Activity.RESULT_CANCELED,则无需使用putExtra,因为没有任何东西可以发回.

最后,您需要在主要活动中添加一些内容,以处理从第二个活动中接收到的结果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_CODE) {

        if (resultCode == Activity.RESULT_OK) {
            int result = data.getIntExtra("pos");
            // do something with the result

        } else if (resultCode == Activity.RESULT_CANCELED) {
            // some stuff that will happen if there's no result
        }
    }
}

为此,我们使用onActivityResult方法.

在此方法的开头,我们正在检查requestCode是否与我们先前定义的相同(作为公共常量,REQUEST_CODE).

如果是,请继续并检查结果的resultCode是什么.如果将数据发送回(Activity.RESULT_OK),我们可以使用getIntExtra()检索它,因为position是整数(类似的,如果要返回字符串,请使用getStringExtra()).然后,您可以对返回的数据进行处理.但是,如果没有将数据发送回去(如我们先前在Activity.RESULT_CANCELED中提到的那样),您可以做其他事情.

希望这可以帮助您实现您的想法,但是Google搜索会找到我上面提到的答案(此处是链接再次),清楚地说明了startActivityForResult()的使用方法.该问题的其他答案也很好地解释了该问题,但是也许您需要有关如何在用例中实现它的指导(即,与您上一个问题中的代码结合使用),这就是为什么我在上面提供了解释./p>

您还可以阅读有关 Android的文档,从活动 以及[[c3>方法]的Android文档( Intent s .

In my app I need to ask the user a quick input.

I need to get a result from this Flash-Activity and then get back to the previous one.

I've read about the StartActivityForResult() method, but I'm not yet sure how to use it properly, any examples?

EDIT:

I've tried to pass the Player object via intent (as the result) using the method I used in all the app applied to this method of the StartActivityForResult():

In my second Activity (the one where I need to get the result from):

Intent intent = new Intent();
Player playerKilled = players.get(position);

Bundle bundle = new Bundle();
bundle.putSerializable("PLAYER_KILLED", (Serializable) playerKilled);
intent.putExtras(bundle);

setResult(Activity.RESULT_OK, intent);
finish();

My Main Activity where I need to take the result to:

if (resultCode == Activity.RESULT_OK) {

    Intent intent = this.getIntent();
    Bundle bundle = intent.getExtras();
    playerKilled = (Player)bundle.getSerializable("PLAYER_KILLED");

    Toast.makeText(this, playerKilled.getName() + "the " + playerKilled.getCardName() + " has died, and he/she had the ID: " + playerKilled.getId(), Toast.LENGTH_SHORT).show();

解决方案

You can request user input in a number of ways, but if you want to use a new Activity, as you mentioned, we can use startActivityForResult() to launch a new activity and return the input from there.

Firstly, I would highly recommend reading through this Stack Overflow answer about how to use startActivityForResult(). I will explain how you can implement it for your specific use case.

So, you need to understand that startActivityForResult() has two parameters:

  • the Intent (which you use to pass data between activities)
  • a "request code" integer that identifies your request

It is good practice to use a constant for your request code that you can access in both of your activities. For example, in your main activity, you could add:

public static final int REQUEST_CODE = 1;

This would be accessible in both activities since it is public, and it would work for a request code since it is an int (integer).

In your main activity, you need an action (such as a button press) to start your second activity. Let's assume it is a button click that triggers this action:

Button button = (Button) findViewById(R.id.your_button);
button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // actions that will happen when the button is pressed:

        Intent intent = new Intent(this, SecondActivity.class);
        startActivityForResult(intent, REQUEST_CODE);
    }
});

Basically, we are creating an Intent which specifies our current activity (this) and the second activity. We use the intent in the startActivityForResult() method along with the REQUEST_CODE we declared earlier.

Now, in our second activity, we need something to trigger the data being returned back. From the previous question you asked, I'm assuming you want data to be returned to the main activity when a RecyclerView item has been clicked. Here is part of my answer to that question modified to show how data will be sent back.

ExampleClickAdapter clickAdapter = new ExampleClickAdapter(yourObjects);
clickAdapter.setOnEntryClickListener(new ExampleClickAdapter.OnEntryClickListener() {
    @Override
    public void onEntryClick(View view, int position) {
        Intent intent = new Intent();
        intent.putExtra("pos", position);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
});
recyclerView.setAdapter(clickAdapter);

The above will send back the position of the list item from the RecyclerView clicked.

Have a look at the Intent's putExtra() method. This is what passes data. You can see that I have passed a String "pos" and the variable for the item position in this method, but why:

intent.putExtra("key", object);

The putExtra method of Intents always use a String key and another object, such as your integer variable, position. The key will be used again when retrieving this object (as I will show you later).

We use Activity.RESULT_OK to say that we are passing a result, but you can use Activity.RESULT_CANCELED if you don't want to send back a result - this is explained in the answer link I mentioned at the beginning. Note that if you use Activity.RESULT_CANCELED, you would not need to use putExtra as there would be nothing to send back.

Finally, you need to add something into your main activity which will deal with receiving the results from your second activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_CODE) {

        if (resultCode == Activity.RESULT_OK) {
            int result = data.getIntExtra("pos");
            // do something with the result

        } else if (resultCode == Activity.RESULT_CANCELED) {
            // some stuff that will happen if there's no result
        }
    }
}

We use the onActivityResult method for this.

At the beginning of this method, we are checking to see if the requestCode is the same as the one we defined earlier (as a public constant, REQUEST_CODE).

If so, we continue and check to see what the resultCode of the result was. If data was sent back (Activity.RESULT_OK), we can retrieve it using getIntExtra() as the position was an integer (similarly, use getStringExtra() if you are returning a String). Then you can do something with the returned data. However, if data was not sent back (as we mentioned earlier with Activity.RESULT_CANCELED), you can do something else.

Hopefully this helps you with implementing your idea, but a Google search would've found the answer I mentioned above (here is the link again) which clearly explained how to use startActivityForResult(). Other answers for this question also explain it well, but perhaps you needed guidance on how to implement it in your use case (i.e. combined with your code from the previous question you had), which is why I've provided the explanation above.

You can also read the Android documentation on Getting a Result from an Activity as well as Android documentation for the [startActivityForResult() method](https://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int)) and Intents.

这篇关于如何使用StartActivityForResult()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆