当您必须替换许多碎片状态时,保存碎片状态的最佳实践方法是什么?

时间:2019-12-31 06:32:08

标签: java android android-fragments

我有一个主要活动,很多片段相互替换,并且状态总是迷路,我什至尝试过public void onSaveInstanceState(@NonNull Bundle outState),但仍然不起作用,我什至在MainActivity中也做了保留实例,但一无所获 现在我有一个CartOrderFragment,当单击按钮时,我会从FoodListFragment向其中添加项目,但是每次我转到CartOrderFragment并返回到FoodListFragment并尝试通过单击同一按钮添加更多项目,CartOrderFragment会丢失其列表。

MainActivity.java

public class MainActivity extends AppCompatActivity implements
     SetupAccountFragment.SetupAccountListener, FoodListFragment.ListenerFoodListFragment,
    SignInAccountFragment.SignInAccountListener, SignUpAccountFragment.SignUpAccountListener {

FragmentManager fm;
FoodListFragment foodListFragment;
ArrayList<Food> foodsOrdered;
CartOrdersFragment cartOrdersFragment;
Map<Integer, Integer> cartValues = new HashMap<>();


@Override
public void sendOrders(ArrayList<Food> foods) {
    foodsOrdered = foods;
}

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    getSupportFragmentManager().putFragment(outState, "myFragment", cartOrdersFragment);
}

// this get called when the button gets clicked in the FoodListFragment
@Override
public void cartClickListener() {
    cartOrdersFragment = CartOrdersFragment.newInstance(foodsOrdered);

    fm.beginTransaction()
            .replace(R.id.main_container, cartOrdersFragment)
            .addToBackStack(null)
            .commit();
}

  // for sign up fragment
@Override
public void registerNowBtnListener() {
    foodListFragment = new FoodListFragment();
    fm.beginTransaction()
            .replace(R.id.main_container, foodListFragment)
            .commit();
  }
// for sign up fragment

// for sign in fragment
@Override
public void signInBtn() {
    foodListFragment = new FoodListFragment();
    fm.beginTransaction()
            .replace(R.id.main_container, foodListFragment)
            .commit();

}
// for sign in fragment

@Override
public void sendToCart(int value, int adapterPosition) {
    cartValues.put(adapterPosition, value);
    foodListFragment.updateCartValue(getTotalValue());
}


private int getTotalValue() {
    int value = 0;
    for (Integer key : cartValues.keySet()) {
        value += cartValues.get(key);
    }
    return value;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState != null) {
        cartOrdersFragment = (CartOrdersFragment) getSupportFragmentManager().getFragment(savedInstanceState,
                "myFragment");
    }

    fm = getSupportFragmentManager();

    Fragment fragment = fm.findFragmentById(R.id.main_container);

    if (fragment == null) {
        // adding fragment to main container
        fm.beginTransaction()
                .replace(R.id.main_container, onBoardingFragment)
                .replace(R.id.id_container_menu, new FoodCategoryFragment())
                .addToBackStack(null)
                .commit();
    }
}
}

CartOrderFragment.java

public class CartOrdersFragment extends Fragment {

private CartOrdersAdapter cartOrdersAdapter;
private ArrayList<Food> foods;
private static final String KEY_ARRAYLIST = "ArrayList";

@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList(KEY_ARRAYLIST, foods);
}

public static CartOrdersFragment newInstance(ArrayList<Food> foods) {
    CartOrdersFragment cartOrdersFragment = new CartOrdersFragment();
    Bundle args = new Bundle();
    args.putParcelableArrayList(KEY_ARRAYLIST, foods);
    cartOrdersFragment.setArguments(args);
    return cartOrdersFragment;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (savedInstanceState != null) {
        foods = savedInstanceState.getParcelableArrayList(KEY_ARRAYLIST);
    }

    if (getArguments() != null) {
        foods = getArguments().getParcelableArrayList(KEY_ARRAYLIST);
    }
    cartOrdersAdapter = new CartOrdersAdapter(getActivity(), foods);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(cartOrdersAdapter);
  }

public class FoodListFragment extends Fragment {
private FoodListAdapter foodListAdapter;
private BadgeHolderLayout badgeHolderLayout;
private ArrayList<Food> foods;

public interface ListenerFoodListFragment {
    void sendToCart(int value, int adapterPosition);
    void cartClickListener();
    void sendOrders(ArrayList<Food> foods);
}

private ListenerFoodListFragment listenerFoodListFragment;

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    try {
        listenerFoodListFragment = (ListenerFoodListFragment) context;
    } catch (ClassCastException e) {
        Log.d("FoodListFragment", "onAttach: " + e.getMessage());
    }
}


@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    foods = new ArrayList<>();

    foods.add(new Food("Chicken", "99999$", R.drawable.chicken));
    foods.add(new Food("Burger", "1000$", R.drawable.burger));


    badgeHolderLayout.setOnClickListener(v -> listenerFoodListFragment.cartClickListener());

    foodListAdapter = new FoodListAdapter(getActivity(), foods, listenerFoodListFragment);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(foodListAdapter);
}

public void updateCartValue(int value) {
    badgeHolderLayout.setCountWithAnimation(value);
}

}

FoodListAdapter.java

public class FoodListAdapter extends RecyclerView.Adapter<FoodListAdapter.ViewHolder>
    implements Filterable {

private Context context;
private List<Food> foodList;
private List<Food> foodListFiltered;
private ArrayList<Food> orderedFood = new ArrayList<>();
FoodListFragment.ListenerFoodListFragment listenerFoodListFragment;

public FoodListAdapter(Context context, List<Food> foodList,
                       FoodListFragment.ListenerFoodListFragment listenerFoodListFragment) {
    this.context = context;
    this.foodList = foodList;
    this.listenerFoodListFragment = listenerFoodListFragment;
    this.foodListFiltered = foodList;
}
}

public class ViewHolder extends RecyclerView.ViewHolder {

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        // this is the button that i mentioned
        tvOk.setOnClickListener(v -> {
            Food food = foodList.get(getAdapterPosition());
            orderedFood.add(food);
            listenerFoodListFragment.sendOrders(orderedFood);
        });
        fc.setOnClickListener(v -> fc.toggle(false));
    }
}
}

1 个答案:

答案 0 :(得分:1)

您可以使用隐藏和显示,试试这个

output_buffering = On