我是使用微调器的新手,我想在OnCreate中使用getSelectedItemPosition,因为我想在微调器项更改时添加一些过滤,我一直在尝试,但仍然在getSelectedItemPosition中得到NULL,我知道我无法初始化onCreate中的setSpinner但我不知道如何解决它
public class FragmentHistory extends Fragment {
public Spinner spinFilter;
private String[] filterView={"Booking","Success"};
public List<Reservation> getData;
private List<historyView> listHistory;
private RecyclerView myRecycleView;
private ProgressDialog progress;
String URL;
private GetURL getURL=new GetURL(URL);
RecycleViewAdapterHistory recycleViewAdapterHistory;
public FragmentHistory(List<Reservation> getData) {
this.getData = getData;
}
public FragmentHistory() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_history, container, false);
setSpinner();
//Create Recycle view
myRecycleView=(RecyclerView)view.findViewById(R.id.history_view);
recycleViewAdapterHistory =new RecycleViewAdapterHistory(getContext(),listHistory);
myRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecycleView.setAdapter(recycleViewAdapterHistory);
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSpinner();
listHistory=new ArrayList<>();
spinFilter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(spinFilter.getSelectedItemPosition()==0){
Toast.makeText(getActivity(),"0",Toast.LENGTH_SHORT).show();
for(int j=0;j<getData.size();j++){
//mydata
}
}else{
Toast.makeText(getActivity(),"1",Toast.LENGTH_SHORT).show();
for(int j=0;j<getData.size();j++){
///mydata
}
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
void setSpinner(){
spinFilter=(Spinner)getView().findViewById(R.id.spinFilter);
ArrayAdapter<String> adapterSpinner= new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item,filterView);
adapterSpinner.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinFilter.setAdapter(adapterSpinner);
}}
答案 0 :(得分:0)
你不需要调用getItemSelectedPosition(),因为 int i (onItemSelected的第三个参数)是所选项目的位置。