2016-08-29 138 views
0

如何在第一個位置向gridview添加新項目。如何將新項目添加到gridview的第一個位置?

protected void showList() { 
    try { 
     JSONObject jsonObj = new JSONObject(myJSON); 
     peoples = jsonObj.getJSONArray(TAG_RESULTS); 

     for (int i = 0; i < peoples.length(); i++) { 
      JSONObject c = peoples.getJSONObject(i); 
      String userid = c.getString(Config.KEY_USERID); 
      String thumburl = c.getString(Config.KEY_THUMBURL); 

      HashMap<String, String> persons = new HashMap<String, String>(); 
      persons.put(Config.KEY_USERID, userid); 
      persons.put(Config.KEY_THUMBURL, thumburl); 

      personList.add(persons); 

     } 

     GridView listview = (GridView) findViewById(R.id.gridview); 
     adapter = new ListViewAdapter(NewRetriveData.this, personList); 
     listview.setAdapter(adapter); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

} 

在那之後我加入新的項目,以動態ArrayList的

HashMap<String, String> persons = new HashMap<String, String>(); 
      persons.put(Config.KEY_USERID, "sweety"); 
      persons.put(Config.KEY_THUMBURL, "www.sweety.com/hello.jpg"); 

之後,我感到重裝ArrayList中

GridView listview = (GridView) findViewById(R.id.gridview); 
     adapter = new ListViewAdapter(NewRetriveData.this, personList); 
     listview.setAdapter(null); 
     listview.setAdapter(adapter); 

我要動態地添加數組項顯示在GridView中第一的位置。

+0

使用它,我想在第一個位置添加新項目不會扭轉電網項目。 –

+0

http://stackoverflow.com/questions/20651946/how-to-set-the-first-item-in-gridview-with-default-value-and-populate-the-rest-o此處引用 –

+0

檢查我的答案。 –

回答

0

首先你全局聲明你的hashmap。 然後在開始循環前添加第一個原始數據。 就是這樣。

0

在適配器

public class CoustomAdapter extends BaseAdapter { 

     Context myContext; 
     private static LayoutInflater inflater = null; 
     ArrayList<HashMap<String, String>> data; 

     public CoustomAdapter(Context context, ArrayList<HashMap<String, String>> data) { 
      myContext = context; 
      this.data = data; 
      inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     } 

     void addItem(HashMap<String, String> persons) { 
      data.add(0, persons); // 0 for add it in starting index 
      notifyDataSetChanged(); 
     } 
    ... 

} 

創建addItem()然後從你的活動

HashMap<String, String> persons = new HashMap<String, String>(); 
     persons.put(Config.KEY_USERID, userid); 
     persons.put(Config.KEY_THUMBURL, thumburl); 

     adapter.addItem(persons); 
相關問題