我正在尝试在我的应用程序中使用片段。当我将应用程序切换到另一个片段时,我试图找到一种方法来存储片段使用的数据。我的第二个片段的代码在下面找到。当切换到这个片段和从这个片段切换时,我正在使用添加和删除片段。这是因为当我使用替换时,我遇到了麻烦。每当我切换到另一个片段并返回到这个片段时,都不会存储计数。我如何实际存储计数,以便在我的片段重新打开时可以回到它?
public class BasicFragment2 extends Fragment {
public int count = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState != null){
count = savedInstanceState.getInt("Integer");
}
View view = inflater.inflate(R.layout.fragment_basic_2, container, false);
Button button = (Button) view.findViewById(R.id.button2);
// A simple OnClickListener for our button. You can see here how a Fragment can encapsulate
// logic and views to build out re-usable Activity components.
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Activity activity = getActivity();
count++;
if (activity != null) {
Toast.makeText(activity, "This is not a fragment...Yes it is " + count, Toast.LENGTH_LONG).show();
}
}
});
return view;
}
public void onSaveInstanceState(Bundle outState){
outState.putInt("Integer",count);
super.onSaveInstanceState(outState);
}
}