我正在创建一个简单的android游戏应用程序,但是我在片段内部的微调器中遇到了一些问题。我尝试了一些解决方案,但我的应用仍然崩溃。有人能帮我吗?大规模的谢谢。
public class SlotMachineFragmentOne extends Fragment {
Spinner dropdown;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_slotmachine_fragment_one, container, false);
initspinnerfooter();
dropdown = rootView.findViewById(R.id.spinner);
return rootView;
}
private void initspinnerfooter() {
String[] items = new String[]{
"Choose apple", "Choose boy", " Choose cat", "Choose dog",
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
} }
答案 0 :(得分:2)
在initspinnerfooter();
之后致电dropdown = rootView.findViewById(R.id.spinner);
赞:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_slotmachine_fragment_one, container, false);
dropdown = rootView.findViewById(R.id.spinner);
initspinnerfooter();
return rootView;
}
答案 1 :(得分:0)
您在初始化之前正在访问dropdown
对象,这就是它抛出NullPointerException
首先进行初始化,然后使用
公共类SlotMachineFragmentOne扩展了片段{
Spinner dropdown;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_slotmachine_fragment_one, container, false);
dropdown = rootView.findViewById(R.id.spinner);
initspinnerfooter();
return rootView;
}
private void initspinnerfooter() {
String[] items = new String[]{
"Choose apple", "Choose boy", " Choose cat", "Choose dog",
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
} }