2017-05-14 53 views
-2

在我的应用程序相同的名单上有装箱一个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.classObj我有这样的代码,将其添加到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中访问和修改。

+0

存储对象的ArrayList,当你需要修改,你是不是实现POJO – jagapathi

+0

@jagapathi的正确形式,你可以请更具体删除对象?这正是我想要做的 – Daniele

+0

将myList引用传递给回收站适配器,以便您不需要为您的mylist类创建新对象 – jagapathi

回答

1

按照我的评论,这是我建议的草案。 请注意我还没有运行这个代码,所以它必须有错误和拼写错误,这只是为了反映我提出的想法。

接收输入的Activity持有创建对象的类的引用以及保存ArrayList的类。

在用户输入时,活动会要求对象创建者创建一个ojbect并将其传递回活动。然后该活动将其添加到列表中。 最后它会通知回收站适配器数据已更改。

在MainActivity:

private CreateObj createObj; 
    private MyList myList; 

    //Other memeber variables for Input elements on the screen 
    //used in createObje.create() to build the new object. 

    public void onCreate(...){ 
     ... 
     createObj = new CreateObj(); 
     myList = new MyList(); 

     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); 

     ...  

     aUserConfirmInputElement.setOnClickListener(new OnClickListener()){ 
      public void onClick(){ 
      Obj obj = createObj.create(); 
      myList.addObjectToList(obj); 

      adapter.notifyDataSetChanged(); 
      } 
     } 

     ... 
}