所以我可以让一个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
,但效果不太好。需要一些洞察力!谢谢您!
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;
}
}
最佳答案
回复这一行:
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