【问题标题】:Send listener between activities在活动之间发送监听器
【发布时间】:2019-03-09 13:03:03
【问题描述】:

我在 FragmentStatePagerAdapter 内部有片段 (x),它在活动 (y) 中,在片段 (x) 中我有 startActivity 到另一个活动 (z),如何将监听器或回调从活动 (z) 发送到活动 (y)

【问题讨论】:

标签: android android-activity activity-lifecycle


【解决方案1】:

你不能。但是您可以使用 startActivityForResult 来启动活动(z)。在activity(z) 活动结束之前,您必须设置一个结果。 然后你可以在activity(y)中处理这个结果。

看看这个 https://developer.android.com/training/basics/intents/result

【讨论】:

    【解决方案2】:

    开始你的第二个活动以获得结果

    static final int PICK_CONTACT_REQUEST = 1;  // The request code
    ...
    private void pickContact() {
        Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
        pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
        startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
    }
    

    然后在完成第二个活动设置结果意图之前

    Intent resultIntent = new Intent()
    resultIntent.putExtra("SOME_TAG", SOME RESULT HERE)
    activity.setResult(Activity.RESULT_OK, resultIntent);
    activity.finish();
    

    然后在第一个活动中,这个意图将在 onActivityResult 方法中处理

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Check which request we're responding to
        if (requestCode == PICK_CONTACT_REQUEST) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                // The user picked a contact.
                // The Intent's data Uri identifies which contact was selected.
    
                // Do something with the contact here (bigger example below)
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 1970-01-01
      • 2015-10-07
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 2018-01-08
      相关资源
      最近更新 更多