在我的应用程序相同的名单上有装箱一个MyList.class
它看起来像这样:Android的 - 获取和修改来自两个不同的活动
public class MyList {
private ArrayList<Obj> objList = new ArrayList<>();
//adds object to list
public void addObjToList(Obj obj) {
objList.add(obj);
}
//gets the whole list
public static ArrayList getObjList() {return objList;}
//gets the size of the list
public static int getObjListSize() {return objList.size();}
//removes obj from list based on his position
public void removeObj(int pos) {
objList.remove(pos);
}
}
从我创建CreateObj.class
的Obj
我有这样的代码,将其添加到objList
:
// creates the new object
Obj newObj = new Obj("Name", 3 /*int*/);
// creates a new List
MyList myList = new MyList();
// adds the obj into the list
myList.addObjToList(newObj);
它成功地将obj添加到列表中。现在从我的Main_Activity.class
我需要找回它,它膨胀成recyclerView,这是我在onCreate()
方法是这样做的:
currentObjList = MyList.getObjList();
//puts list into recycler
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false));
adapter = new RecyclerAdapter(this, currentObjList);
recyclerView.setAdapter(adapter);
注意,因为我想要的清单是我没有设置MyList myList = new MyList()
我Main_Activity在CreateObj类中创建的一个。
很明显,这不是正确的做法,因为如果我们说我想从recyclerView中删除一个元素,我需要从objList(在MyList.class)中删除它,那不是因为我不能访问MyList.class方法而不设置new MyList()
,如果我将它设置为new,它将不会保留从CreateObj类添加的Obj。
简而言之:我怎样才能让相同的objList可以从CreateObj.class和Main_Activity.class中访问和修改。
存储对象的ArrayList,当你需要修改,你是不是实现POJO – jagapathi
@jagapathi的正确形式,你可以请更具体删除对象?这正是我想要做的 – Daniele
将myList引用传递给回收站适配器,以便您不需要为您的mylist类创建新对象 – jagapathi