2011-10-17 174 views
4

我目前有一個自定義列表視圖,其中列表中的每個項目包含兩行文本。我想要做的是每次用戶點擊按鈕時,它會在用戶輸入的文本列表上創建一個新項目。雖然我知道如何獲取文本,但我無法將新項目添加到列表視圖,因爲我根本不知道從哪裏開始。Android - 將項目添加到按鈕上的自定義列表視圖點擊

這裏是我的代碼:

public class MainFeedActivity extends ListActivity implements OnClickListener { 
    View sendButton; 
    EditText postTextField; 
    TextView currentTimeTextView, mainPostTextView; 
    ListView feedListView; 
    String[] test; 
    ArrayList<HashMap<String, String>> list; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main_feed); 

     //create button and implement on click listener 
     sendButton = this.findViewById(R.id.sendPostButton); 
     sendButton.setOnClickListener(this); 

     list = new ArrayList<HashMap<String, String>>(); 

     //create the adapter for the list view 
     SimpleAdapter adapter = new SimpleAdapter(
      this, 
      list, 
      R.layout.post_layout, 
      new String[]{"time", "post"}, 
      new int[]{R.id.postTimeTextView, R.id.postTextView}); 
     //fill the list view with something - TEST 
     fillData(); 
     //set list adapter 
     setListAdapter(adapter); 
    } 

    public void fillData() { 
     //long timeTest = System.currentTimeMillis(); 
     HashMap<String, String> temp = new HashMap<String, String>(); 
     temp.put("time", "current time"); 
     temp.put("post", "USER TEXT GOES HERE"); 
     list.add(temp); 
    } 

    @Override 
    public void onClick(View button) { 
     switch (button.getId()) { 
      case R.id.sendPostButton: 
       break; 
     } 
    } 
} 

回答

7

這是添加新的元素添加到ArrayList(就像你在做fillData),然後調用adapter.notifyDataSetChanged()一樣簡單。

1

調用fillData()後,只需撥打adapter.notifyDataSetChanged()即可。

NotifyDataSetChanged() - 通知附加的View,底層數據已被更改,並且應該自行刷新。

相關問題