3
我正在試驗在我的應用程序中使用片段。我試圖找到一種方法來存儲我的應用程序切換到另一個片段時使用的片段數據。我的第二個片段的代碼如下。當切換到和從這個片段我使用添加和刪除片段。這是因爲當我使用替換時,我遇到了麻煩。每當我切換到我的其他片段,並返回到這一個,計數不會被存儲。我如何實際存儲計數,以便在我的碎片再次打開時再次回到它?片段onSaveInstanceState未被調用
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);
}
}
究竟將這種數據傳遞給我的活動的最佳方式是什麼?我應該在我的片段中創建兩個方法來與活動來回傳遞數據嗎?或者有沒有一種方法可以像全局變量一樣使用。 – Mbhammerbro
定義片段中的公共方法(例如'getCount' /'setCount'),然後在活動中獲取片段的引用並調用定義的方法來獲取或設置片段中的計數值 – waqaslam