Android - adding an item to a custom listview when a button is clicked

I currently have my own list in which each item in the list contains two lines of text. What I would like to do is each time the user clicks the button, he creates a new item in the list with text that the user enters. Although I know how to get text, it's hard for me to add a new item to the list, since I just don't know where to start.

Here is my code:

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; } } } 
+4
source share
2 answers

It is as simple as adding a new element to your ArrayList (as you do in fillData ), and then calling adapter.notifyDataSetChanged() .

+7
source

After calling fillData (), just make adapter.notifyDataSetChanged() call.

NotifyDataSetChanged () - Notifies the attached view that the underlying data has been changed and should be updated.

+1
source

All Articles