Reputation: 481
I have a Activity that's creating a Check list, if I close the activity with back Button the list is saved in a Database.
The list from the Database is used as the MainActivity content.
This is how my app will look:
If I press the List Item button, a new element should be added to the list. How can I add and sisplay a new Item (Layout with Checkbox and EditText)?
Do I need an Adapter? I don't want the 'list item' part repeated.
That looks so after i press 4 times
Upvotes: 1
Views: 8205
Reputation: 21733
Activity
private ArrayAdapter mAdapter;
onCreate
ListView lv = (ListView) findViewById(R.id.my_list);
List<String> initialList = new ArrayList<String>(); //load these
mAdapter = new ArrayAdapter(this, android.R.id.text1, initialList)
lv.setadapter(mAdapter);
When the event happens
mAdapter.add(newString);
The add method in ArrayAdpater will automatically take care of the notifyDataSetChanged()
call for you and update the display.
TextWatcher you might not need this part, it's if you want the text added as soon as the text is changed which your question seems to indicate - that is risky because you might get partial entries, so i recommend a done button instead, in which case you just do the afterTextChanged
stuff in the onClick
method.
EditText editText = (EditText) findViewById(R.id.my_edit_text);
editText .addTextChangedListener(new TextWatcher(){
@Override
public void afterTextChanged(Editable arg0) {
//TODO: check it isnt emtpy
String text = arg0.getText().toString();
mAdapter.add(text);
//Hide the add item views again
arg0.setText("");
arg0.setVisibility(View.GONE);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) { /*nothing*/ }
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) { /*nothing*/ }
});
Upvotes: 2
Reputation: 4959
You can add plus button in your list as footerview as your image then new item add in your arraylist by the action(onClicklistener) of footer view button then call youradapter.notifyDataSetChanged().
Upvotes: 0