Using PlacePicker in a fragment

时间:2016-07-11 19:07:27

标签: android android-fragments gmsplacepicker

I am trying to use the google placepicker from within a fragment that is part of my Android app. I cant seem to use the data being returned by the onActivityResult. I used a solution from (https://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en) to get the results back within a fragment. However this solution doesnt allow me to change elements in my view based on input from my placePicker. The toast with the place info works but not changing the button because its outside the inflated view. I am using fragments because my app is a tabbed slider app with 2 fragment, creating location and viewing locations.

Please help and ask for clarification if necessary!

Here is the onCreateView in myFragment extends Fragment class:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_make_minyan, container, false);

    //Map Place Activity
    final Button locationButton = (Button) rootView.findViewById(R.id.button_location);
    locationButton.setOnClickListener(new View.OnClickListener() {
        //int RESULT_OK;
        public void onClick(View v) {
            PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
            try {
                getActivity().startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            }
        }
    });
    //a bunch of other buttons and spinner etc that are working.

    return rootView;
}

And here is the onActivityResult code used from the solution linked above. The commented out line is the line of code that wont work currently.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == Activity.RESULT_OK) {
            Place place = PlacePicker.getPlace(data, getActivity());
            //locationButton.setText(String.format("Place: %s", place.getName()));
            String toastMsg = String.format("Place: %s", place.getName());
            Toast.makeText(getContext(), toastMsg, Toast.LENGTH_LONG).show();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果你编写了getActivity()。startActivityForResult(...),那么onActivityResult将在你的Activity中被调用,而不是在你的片段中。

尝试使用startActivityForResult(...)