【发布时间】:2017-09-07 21:52:32
【问题描述】:
我正在尝试传递一个自定义 POJO,它将 Parcelable 作为 Bundle 从我的 Activity 扩展到我的 Fragment。填充的捆绑对象成功传递给我的 Fragment 的 newInstance 方法。但是,在我的 Fragment 的 onCreate 方法中,当我尝试恢复 POJO 类的这个 ArrayList 时,它会以某种方式被丢弃。
//Activity
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_detail);
mRecipe = getIntent().getParcelableExtra("com.wernerraubenheimer.bakingapp.data.RecipeModel");
//This works mRecipe is successfully populated with my custom ArrayList<IngredientModel>
//My class IngredientModel extends Parcelable
IngredientListFragment ingredientListFragment = IngredientListFragment.newInstance(mRecipe.getIngredients());
//Still good so far....
getSupportFragmentManager()
.beginTransaction()
.add(R.id.first_fragment_container, new IngredientListFragment())
.commit();
}
//Fragment
public static IngredientListFragment newInstance(ArrayList<IngredientModel> ingredients) {
IngredientListFragment ingredientListFragment = new IngredientListFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("ingredients", ingredients);
ingredientListFragment.setArguments(bundle);
return ingredientListFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This is where the ball gets dropped, mIngredientList which I initialized when I declared it just after
//class declaration: private ArrayList<IngredientModel> mIngredientList = new ArrayList<>();
//is now empty??
//I have also placed the call to super.onCreate after the statement below
mIngredientList = getArguments().getParcelableArrayList("ingredients");
//have also used savedInstanceState
}
我想在 Fragment 的 onCreateView 中的 RecyclerView 中使用 ArrayList:
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_ingredient_list, container, false);
rvIngredientList = (RecyclerView)rootView.findViewById(R.id.rv_ingredient_list);
ingredientLayoutManager = new LinearLayoutManager(getActivity());
ingredientLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvIngredientList.setLayoutManager(ingredientLayoutManager);
IngredientListAdapter ingredientListAdapter = new IngredientListAdapter(mIngredientList);
rvIngredientList.setAdapter(ingredientListAdapter);
return rootView;
}
【问题讨论】:
标签: android android-fragments android-activity