何时在片段中显示下拉列表 window?

When to show a dropdown window in a fragment?

我在尝试 autocompleteTextView.showDropDown() 时遇到以下错误:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

我已经尝试在各种 Fragment 生命周期方法中做到这一点。总是弹出这个错误。

我在哪里调用在片段中显示额外 windows 的方法?

编辑:

@BindView(R.id.acService) AutoCompleteTextView autocompleteSTextView;

@Override
public void onAttach(Context context)
{
    super.onAttach(context);
    this.context = context;
}

@Override
public void onDetach()
{
    super.onDetach();
    context = null;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    return inflater.inflate(R.layout.fragment_home, container, false);
}

@Override
public void onResume()
{
    initialize();
    loadSkillsData();
    super.onResume();
}

private void initialize()
{
    util = new Util(context);
    requestService = new RequestService();
    requestService.setServerUserId(getUser().getServerUserId());
    geoDataClient = Places.getGeoDataClient(context);

    autocompleteAdapter = new PlaceAutocompleteAdapter(context, geoDataClient, BOUNDS_WORLD, null);
    autocompleteTextView.setAdapter(autocompleteAdapter);

    mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment);
    mapFragment.getMapAsync(this);

    autocompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View view, boolean hasFocus)
        {
            if(hasFocus)
            {
                autocompleteService.showDropDown();
            }
        }
    });
}

下面是片段在 Activity 中的加载方式。我正在使用 MaterialNavigationDrawer:

private void replaceWithFragment(Fragment fragment)
{
    getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment).commit();
    navigationDrawer.closeDrawer();
}

onFocusChange() 可以在任何内容实际可见之前调用。

改变

if(hasFocus)
{
    autocompleteService.showDropDown();
}

if(hasFocus && isVisible())
{
    autocompleteService.showDropDown();
}

这将确保片段实际显示并添加到 Window,然后再尝试显示下拉列表。