我有:
包含类别微调器的片段1,imageView。
片段2包含后退按钮。
开始时我选择一个微调器类别的值,之后当我从画廊下载画面时,微调器的值会改变并返回到它的初始位置0,当我点击片段2上的按钮时,它也是同样的问题。
我正在使用spinner.setSelection(poisition)
叮叮当然但是我不知道我在片段中的哪个位置!
那么,即使我从图库中获取图像或单击后退按钮,如何保留微调器的选定值?
CrateView的来源:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_add_book_photos,
container, false);
auth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance();
myRef = mDatabase.getReference("categories");
spinnerCat = (Spinner) rootView.findViewById(R.id.spinner_cat_book);
selectImage = (ImageView) rootView.findViewById(R.id.book_picture);
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<String> catListBook = new ArrayList<String>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Categoriesbook book = snapshot.getValue(Categoriesbook.class);
String catBook = book.getNom_cat();
catListBook.add(catBook);
}
ArrayAdapter<String> catAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, catListBook);
spinnerCat.setAdapter(catAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
spinnerCat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
catlivre = (String) parent.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
selectImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showFileChooser();
}
});
return rootView;
}
答案 0 :(得分:1)
试试这个:
使用SharedPreferences
保存Spinner
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
catlivre = (String) parent.getItemAtPosition(position);
int selected_item = spinner.getSelectedItemPosition();
SharedPreferences sharedPref = getActivity().getSharedPreferences("Position",0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("spinner_item", selected_item);
prefEditor.commit();
}
现在,在您的Framgent的onCreateView()
中,您可以在开头加载上一个选定的微调器位置:
SharedPreferences sharedPref = getActivity().getSharedPreferences("Position", Context.MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("spinner_item",-1);
if(spinnerValue != -1) {
// set the value of the spinner
spinner.setSelection(spinnerValue,true);
}
答案 1 :(得分:0)
片段通过调用Fragment生命周期中定义的回调来告诉您它何时出现。 https://developer.android.com/guide/components/fragments.html
您需要做的就是在这些回调中对状态存储和检索进行编码。