spinner won't populate from my array [duplicat

2019-08-31 05:15发布

问题:

This question is an exact duplicate of:

  • Spinner will not populate and won't set arrayadapter

My app redirects me to a different screen from my home with the tap of a button. Once, i reach my city screen my spinner is visible. But it doesn't contain any elements from my array. Nothing force closes or anything, but it doesn't work.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_city);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
    }       
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_city, container, false);

    String[] test = {"test1", "test2"};
    Spinner spin = (Spinner) v.findViewById(R.id.countries);
    ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, test);
    adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spin.setAdapter(adapt);
    return v;
}

回答1:

You need to have the below.

 public static PlaceHolderFragment extends Fragment
   {
     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_city, container, false);

    String[] test = {"test1", "test2"};
    Spinner spin = (Spinner) v.findViewById(R.id.countries);
    ArrayAdapter<String> adapt = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, test);
    adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spin.setAdapter(adapt);
    return v;
    }
   }

Also use getActivity() to get the context of hosting activity.