OnPlaceSelectedListener of SupportPlaceAutocompleteFragment not fired inside ViewPager

懵懂的女人 提交于 2019-12-04 10:22:19

From the docs:

If your fragment is nested within another fragment, your app must also forward onActivityResult() calls to the containing fragment, as shown in the following snippet:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    autocompleteFragment.onActivityResult(requestCode, resultCode, data);
}

Perhaps this is the solution.

The @AndrewR answer took me on the right track, very similar to the comments, I override onActivityResult however it didn't work.

The problem was the host Activity wasn't calling the super:

public class HostActivity extends AppCompatActivity {

    //Please don't forget other relevant methods

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //super.onActivityResult... is the important line
        //Add other custom behaviours
    }
}

Assuming the Google Places API for android services are properly enabled for your api key, even I observed similar issue using SupportPlaceAutocompleteFragment, where the onPlaceSelected is never getting triggered on place selection. However later when i tried with the intent approach, things worked..

I ran into this issue this morning, and after a bunch of reading and random similar issues I got the following to work.

If you look at the source code for SupportPlaceAutocompleteFragment you will see it calls

public class SupportPlaceAutocompleteFragment extends Fragment {
    private void zzzG() {
        ...
        try {
            Intent var2 = (new IntentBuilder(2)).setBoundsBias(this.zzaRk).setFilter(this.zzaRl).zzeq(this.zzaRj.getText().toString()).zzig(1).build(this.getActivity());
            this.startActivityForResult(var2, 1);
        }
        ...
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 1) {
            ...
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

Depending on your integration this can cause the RequestCode to change to something other than 1. By extending it to override the startActivityForResult you can change the behaviour by calling getActivity().startActivityForResult instead of this.startActivityForResult

public class WrappedSupportPlaceAutocompleteFragment extends SupportPlaceAutocompleteFragment {
@Override
public void startActivityForResult(Intent intent, int requestCode) {
    this.getActivity().startActivityForResult(intent, requestCode);
}

}

from there you can now follow what AndrewR mentioned and pass the activity result from the activity to the fragment and get the expected result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!