我只使用replace附加到一个活动的一个片段。当设备在几秒钟后锁定屏幕然后解锁时,即使片段视图(EditTexts等)和微调器选定项保持不变,也会执行分配给某个微调器的onItemSelected方法。
public class MyFragment extends Fragment {
private Spinner mySpinner;
public static MyFragment newInstance() {
return new MyFragment();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.some_layout, container, false);
mySpinner = (Spinner)view.findViewById(R.id.my_spinner);
List<String> items = new ArrayList<>();
items.add("Anything");
items.add("Anything");
items.add("Anything");
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(
getContext(),
android.R.layout.simple_spinner_item,
items);
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "Hello World", Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
每次我选择一个项目时,我都会收到toast消息“Hello World”(或者分配给监听器的任何其他方法或动作),但是当设备锁定然后我解锁时,我仍然会收到消息,好像调用onItemSelected方法。
我一直在尝试使用布尔值和Fragment的onSaveInstanceState和onActivityCreated方法,但我还没有找到一种方法来阻止onItemSelected方法在设备从锁定屏幕返回时执行。
答案 0 :(得分:0)
问题是在onItemSelected
初始化后调用Spinner
,解决方案是在mySpinner.setSelection(position, false)
之前放置mySpinner.setOnItemSelectedListener
参考this