简体   繁体   English

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

[英]how to pass map data from an activity to a fragment?

I have a main activity that has a fragment (firstFragment). 我的主要活动有一个片段(firstFragment)。 in this fragment I have a map button that open the map activity. 在此片段中,我有一个打开地图活动的地图按钮。 in this map activity I put the latitude and longitude of a point in bundle and finish the activity and go back to firstfragment. 在此地图活动中,我将点的纬度和经度捆绑在一起,然后完成活动并返回至第一片段。 in firstfragment I want to get the bundle and show the latitude. 在第一片段中,我想获得捆绑包并显示纬度。 how can I do this? 我怎样才能做到这一点?

refering to the official, api: 指官方api:

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

you should use the method 你应该使用方法

 startActivityForResult()

on the fragment. 在片段上。

usage example: 用法示例:

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

and implement this method: 并实现此方法:

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

and something like this on your map activity, called inside the code where you close it, your "onStop","onCancel", "onbackPressed", whatever you use to close it: 以及在地图活动中这样的代码,在您将其关闭的代码中调用了“ 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM