Android: spinner works in Activity but not Fragmen

2019-05-24 11:26发布

问题:

So I was able to make a Spinner work in a single Activity, but when I transferred the code to a Fragment it obviously didn't work.

I am getting an error in these two lines:

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category_array, android.R.layout.simple_spinner_item);
ArrayAdapter<String> adapterItem = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, suggestedItems);

and I know that the context this needs to be changed. I already tried to use getActivity(), but that didn't work as well.

Some insight needed! Thank you!

public class NominateFragment extends Fragment {

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

    View view = inflater.inflate(R.layout.fragment_nominate_page, container, false);

    //SPINNER
    Spinner spinner = (Spinner)getView().findViewById(R.id.category);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category_array, android.R.layout.simple_spinner_item); // Create an ArrayAdapter using the string array and a default spinner layout
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
    spinner.setAdapter(adapter);    // Apply the adapter to the spinner

    //AUTOCOMPLETE
    AutoCompleteTextView nominateItem = (AutoCompleteTextView)getView().findViewById(R.id.autocomplete_nominate_item); // Get a reference to the AutoCompleteTextView in the layout
    String[] suggestedItems = getResources().getStringArray(R.array.suggested_items_array); // Get the string array
    ArrayAdapter<String> adapterItem = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, suggestedItems);     // Create the adapter and set it to the AutoCompleteTextView 
    nominateItem.setAdapter(adapterItem);

    return view;
}

}

回答1:

replce this line:

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category_array, android.R.layout.simple_spinner_item);

with

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item);

and this line:

Spinner spinner = (Spinner)getView().findViewById(R.id.category);

with:

Spinner spinner = (Spinner)view.findViewById(R.id.category);

and:

AutoCompleteTextView nominateItem = (AutoCompleteTextView)getView().findViewById(R.id.autocomplete_nominate_item); // Get a reference to the AutoCompleteTextView in the layout

with:

AutoCompleteTextView nominateItem = (AutoCompleteTextView)view.findViewById(R.id.autocomplete_nominate_item); // Get a reference to the AutoCompleteTextView in the layout