Friday, December 3, 2010

Repainting a ListView Adapter from a Separate Activity

Basically, I have a page with a search box. You search for something, get the results in the form of a list on a pop-up dialog (which has its own activity). When you select one of the results, the dialog closes, and the item is added to the original page with the search box. You can repeat this, ad nauseum. *NOTE* This method requires an API level of at least 1.6.

PageOne.java
Be sure to declare variables for the strings and adapter before onCreate. Static makes it available to use by other activities in the package:


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


Define these variables inside onCreate:


strings = new ArrayList<String>();   
lv = getListView();
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, strings);
lv.setAdapter(adapter);


PageTwo.java

In the onClick method, add code to transform selected item to a string value. Then, adds the item to the String Array in PageOne. Last, notifyDataSetChanged on the adapter used in pageone:


@Override  
public void onListItemClick(ListView parent, View v, int position, long id) {  
selected = ((TextView) v).getText().toString();  
PageOne.strings.add(selected);  
((ArrayAdapter<String>) PageOne.adapter).notifyDataSetChanged();  
this.finish();  
}

No comments:

Post a Comment