2017-05-14 22 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(); 
      } 
     } 

     ... 
} 
相關問題