Wednesday, February 9, 2011

Deleting Single Choice Listview Items

This post assumes you know how to create a single choice listview and a button in xml.

1) First, define these three variables:


     public static List<String> strings;
     public static ListAdapter adapter;
     ListView lv;

2) Next, set up the listview in onCreate:


     strings = new ArrayList<String>();
     lv = getListView();
     adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice, strings);
     lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
     lv.setAdapter(adapter);



3) Last, set up the delete button:


     Button btnRemove = (Button) findViewById(R.id.ButtonEditLabOrderForm_Remove);
     btnRemove.setOnClickListener(new View.OnClickListener() {
          @SuppressWarnings("unchecked")
          public void onClick(View v) {
               // Code below only works with ONE CHECKED ITEM at a time
               int len = lv.getCount();
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = strings.get(i);
// do whatever you want with the checked item
strings.remove(item);
((ArrayAdapter<String>) adapter).notifyDataSetChanged();
}
   }
     });

Thats it !

Still trying to figure out how to delete multiple items in a multiple choice list :(

Tuesday, February 1, 2011

Button with Image and Text

This all goes down in the XML file with the button in question. This can also be accomplished dynamically (not shown.) Here is the excerpt from the xml file defining the button. The image should be located in the drawable folder. The image is called from android:drawable. Use drawableLeft, drawableRight, drawableTop, drawableBottom depending on how you want to place the image in relation to the text. Adjust the padding to suit your aesthetic.



<Button
    android:layout_width="wrap_content"
    android:text="Sample Text"
    android:id="@+id/Button01"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/search"
    android:drawablePadding="0px"
    android:padding="0px">
</Button>