如何将地图数据从活动传递到片段?

时间:2015-04-13 15:13:02

标签: android

我有一个主要活动,它有一个片段(firstFragment)。在这个片段中,我有一个打开地图活动的地图按钮。在这个地图活动中,我将一个点的纬度和经度放在束中并完成活动并返回到firstfragment。在firstfragment中,我想获得捆绑并显示纬度。 我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

参考官方,api:

http://developer.android.com/training/basics/intents/result.html

你应该使用方法

 startActivityForResult()
片段上的

用法示例:

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

并实现此方法:

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

在您的地图活动中有类似的内容,在您关闭它的代码内部调用,您的“onStop”,“onCancel”,“onbackPressed”,无论您使用什么来关闭它:

private void finishWithResult()
{
    Bundle conData = new Bundle();
    conData.putFloat("lat", 0.0);
 conData.putFloat("lon", 0.0);
    Intent intent = new Intent();
    intent.putExtras(conData);
    setResult(RESULT_OK, intent);
    finish();
}