我正在做一个android项目,尝试使用片段
我的一个片段有一个微调器,为此我需要一个单独的侦听器
当我设置侦听器时,由于需要此对象,因此将一个对象发送给构造函数,但我不知道为什么在片段中调用它而在侦听器中对其进行更新时,总会得到null
也许我必须使用另一种方式来传递对象,但是我没有找到任何
如果您能帮助我知道为什么[chosenTrackable]在片段中始终为null,将不胜感激。 以及是否有更好的方法在片段和侦听器之间调用对象
这是我的代码:
public class AddTracking extends Fragment {
Spinner trackableSpinner;
Context context;
HashMap <Integer, MyTrackable> myTrackables ;
MyTrackable chosenTrackable;
private static final String TAG = "AddTracking";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = container.getContext();
View view = inflater.inflate(R.layout.fragment_add_tracking, container, false);
myTrackables= new Model(view.getContext()).getTrackables();
//initilizing
trackableSpinner = view.findViewById(R.id.trackable_spinner);
//setup trackable spinner
ArrayAdapter trackableSpinnerAdapter = new ArrayAdapter(this.getActivity(),
android.R.layout.simple_spinner_item, new ArrayList<>(myTrackables.values()));
trackableSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
trackableSpinner.setAdapter(trackableSpinnerAdapter);
trackableSpinner.setOnItemSelectedListener( new SpinnerTrackableItemSelectedListener(this.getActivity(),chosenTrackable));
chosenTrackable = myTrackables.get(trackableSpinner.getSelectedItemPosition());
Log.d(TAG, "onCreateView: " + chosenTrackable);
return view;
}
}
收听者:
public class SpinnerTrackableItemSelectedListener implements AdapterView.OnItemSelectedListener {
Context context ;
private static final String TAG = "SpinnerTrackableItemSel";
MyTrackable chosenTrackable;
public SpinnerTrackableItemSelectedListener(Context context, MyTrackable chosenTrackable) {
this.context = context;
this.chosenTrackable = chosenTrackable ;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
chosenTrackable = (MyTrackable) parent.getAdapter().getItem(position);
Log.d(TAG, "loadTimeSpinner: " + chosenTrackable);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}