恢复后面片段中的值

时间:2018-01-07 16:12:44

标签: android android-fragments

这是我的Fragment.class .....我得到了完美的价格但是一旦片段被重新按下并再次创建,总价格总是显示0 ...这就是重新创建的总价格值。 ...请每次新创建时帮我存储价值......

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cart_product_list, container,false);
subTotal = (TextView ) view.findViewById(R.id.sub_total);
totalPrice = totalPrice.add(price);
subTotal.setText("Total: " + totalPrice + " $");
return view;
}

2 个答案:

答案 0 :(得分:0)

您必须使用SharedPreferences保存如下所示的值 在onPause of fragment

中保存totalPrice,如下所示
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("totalPrice", totalPrice);
editor.commit();

回来时回读onCreate

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
totalPrice = sharedPref.getInt(totalPrice, defaultValue);

答案 1 :(得分:0)

您必须在onStart中编写代码,以便在按下后退时重新加载。 (也就是说,假设您拥有totalprice的值,并且想要在按下后退时正确加载它,请尝试此代码..)

public void onStart() {
        super.onStart();
        subTotal = (TextView ) view.findViewById(R.id.sub_total);
        totalPrice = totalPrice.add(price);
        subTotal.setText("Total: " + totalPrice + " $");
 }
相关问题