【发布时间】:2018-04-20 07:58:49
【问题描述】:
我想单击一个按钮,将一堆新对象添加到另一个活动的回收站视图中。
我有活动 A(食谱页面)和活动 B(购物清单)。我在活动 A 中有一个菜单按钮,用于将数组的所有项目(成分)添加到活动 B 的 Recycler View ArrayList。
我在活动 A 中有一个循环来遍历数组的每个成分:
for (int x = 0; x < recipeIngredients.length; x++) {
ShoppingList.insertItem(recipeIngredients[x]);
}
还有一个活动 B 中的方法,我在活动 B 中使用该方法将单个项目添加到回收站视图。但是当在活动 A 中调用时(如上),我得到空对象引用。
购物清单活动:
private RecyclerView mRecyclerView;
public RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public static ArrayList<ShoppingItem> mShoppingList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
mRecyclerView = findViewById(R.id.shopping_listView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ShoppingListAdapter(mShoppingList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
public void insertItem(String ingredient) {
mShoppingList.add(new ShoppingItem(ingredient));
mAdapter.notifyDataSetChanged();
}
【问题讨论】:
-
你能在
onCreate中调用insertItem函数吗? -
启动另一个activity时,可以使用bundle将对象列表传递给另一个activity,以便在RecyclerView上显示
-
在同一个活动中,是的,我确实在 oncreate 中添加了项目。但我还需要从另一个活动中添加它们
-
我认为您可以更好地解释它。使用ActivityA启动ActivityB,List在ActivityA中,......等等
-
@sontruongit 我在按下它后并没有开始活动,我只想单击按钮并保持在同一页面上,同时添加项目。捆绑包可以解决这个问题吗?
标签: java android android-recyclerview