setOnItemSelectedListener似乎只在第一次启动应用程序时起作用

时间:2017-05-30 09:36:49

标签: android-fragments drop-down-menu android-spinner

我在片段的菜单中使用微调器,将其数据加载到onCreateView中。当应用程序启动时它可以正常工作,但是,当用户导航到另一个片段并返回或下次打开应用程序时,微调器会消失。

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    setHasOptionsMenu(true);  
    getSpinnerValues(); //string request to add values to TrailList
}



 @Override                                                               // ...
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.map_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);  //temp
    //setData();

    final MenuItem item = menu.findItem(R.id.trailfiller);
    mySpinner = (Spinner) MenuItemCompat.getActionView(item);
    ArrayAdapter<Trail> adapter = new ArrayAdapter<Trail>(getContext(), android.R.layout.simple_spinner_dropdown_item, TrailList); 
    mySpinner.setAdapter(adapter);

    mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Trail country = (Trail) parent.getSelectedItem();
            Toast.makeText(getContext(), ""+country.getId()+""+country.getName(), Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
}

when the fragment is first loaded spinner is gone when the user navigates to a different fragment

当它变为空白时,onItemSelected也不会被触发。需要注意的是,当值被硬编码时,微调器是一致的。我在这里错过了什么?

1 个答案:

答案 0 :(得分:0)

onItemSelected将被触发.Problem使用大小为0的ArrayList。在onCreateOptionsMenu中填充它将有所帮助。或者,您可以将项添加到onCreateOptionsMenu内的列表中,这将帮助您摆脱此问题

Spinner spinner= new Spinner();
    spinner.setName("select a country");
    TrailList.add(spinner);