I am making an android application that needs to add items to a dynamic ListView. How can I do this? I wish to add the item once the "AddItemToListViewButton" is pressed. I am trying to use the code below, but however, it’s not working. How can I fix/make this happen? My code:
public class NotesActivity extends ListActivity implements OnClickListener {
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
Button AddItemToListView, AddItemToListViewButton;
LinearLayout AddItemToListViewLinearLayout;
static final String[] COUNTRIES = new String[] {
"Matte på A1 med Ole", "Engelsk på klasserommet", "Film på A1 etter friminuttet"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "Note: " + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu meny) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listviewmenubuttons, meny);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.AddItemToListView:
AddItemToListViewEditText = (EditText)findViewById(R.id.AddItemToListViewEditText);
AddItemToListViewButton = (Button)findViewById(R.id.AddItemToListViewButton);
AddItemToListViewLinearLayout = (LinearLayout)findViewById(R.id.AddItemToListViewLinearLayout);
AddItemToListViewButton.setOnClickListener(this);
AddItemToListViewLinearLayout.setVisibility(View.VISIBLE);
break;
}
return true;
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.AddItemToListViewButton:
myList.add("Hello");
myList.add("world");
System.out.println("The list contains " +
myList.size() + "elements, and " +
"the first is " + myList.get(0));
AddItemToListViewLinearLayout.setVisibility(View.GONE);
break;
}
}
}
Your
ListActivityhas aListViewelement that is based on anArrayAdapter<String>containing a string array named COUNTRIES. In youronClick()method you add strings to anArrayList<String>(myList) but yourListViewadapter doesn’t know about it and that you try to add it to your list(well this is what i think you are trying to do). So :-in your
myListadd the current content of yourCOUNTRIESstring array:-set the adapter to point to the
myList:-in your
onClick()method write: