java - Adding a remove button to each listView element -
i'm learning android , struggling part. have simple activity button adds entries listview in array list. point down road make favorites tab app display items have selected favorite in activity. haven't progressed far yet i'm playing , add remove buttons on each row remove "item." here have far.
public class mainactivity extends listactivity { arraylist<string> listitems = new arraylist<string>(); arrayadapter<string> adapter; int click=1; public void additems(view v) { listitems.add("soon item : " + click++); adapter.notifydatasetchanged(); } @override public void oncreate(bundle icicle) { super.oncreate(icicle); setcontentview(r.layout.activity_main); adapter=new arrayadapter<string>(this, android.r.layout.simple_list_item_1, listitems); setlistadapter(adapter); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.menu_main, menu); return true; } @override public boolean onoptionsitemselected(menuitem item) { // handle action bar item clicks here. action bar // automatically handle clicks on home/up button, long // specify parent activity in androidmanifest.xml. int id = item.getitemid(); //noinspection simplifiableifstatement if (id == r.id.action_settings) { return true; } return super.onoptionsitemselected(item); }
xml file
<linearlayout xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:weightsum="1" tools:context="com.favtest2.mainactivity"> <button android:id="@+id/addbtn" android:text="add new item" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onclick="additems" android:layout_gravity="right" /> <listview android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawselectorontop="false" />
for list item using standard layout framework:
android.r.layout.simple_list_item_1
there's no button.
create custom layout button "delete" instead.
but don't need button - can click right on list item delete itself.
look info onitemclicklistener.
here pretty tutorial:
http://www.vogella.com/tutorials/androidlistview/article.html
upd:
add code method, like:
@override protected void onlistitemclick(listview l, view v, int position, long id) { listitems.remove(position); adapter.notifydatasetchanged(); }
Comments
Post a Comment