spinner won't populate from my array [duplicat

2019-08-31 04:32发布

This question is an exact duplicate of:

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条回答
够拽才男人
2楼-- · 2019-08-31 05:11

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.

查看更多
登录 后发表回答