Android:spinner在Activity中工作但不在Fragment中工作

时间:2013-12-09 01:02:01

标签: android spinner fragment

所以我能够在一个Spinner中进行Activity工作,但是当我将代码转移到片段时,它显然无效。

我在这两行中遇到错误:

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);

我知道需要更改上下文this。我已经尝试使用getActivity(),但这也不起作用。

需要一些见解!谢谢!

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 个答案:

答案 0 :(得分:7)

替换此行:

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

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

和这一行:

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

使用:

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

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

使用:

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