Umang
Umang

Reputation: 593

one activity, multiple views?

I want to design a list with options to sort it in ascending or descending orders. I am able to do that using different intents. Is there a way to do that without having a new intent? The example that comes to my mind is Manage Applications in android. Sort by name and size happen on the same screen. How is that done?

Edit - I have a list of say 20 items. Right now, I am sorting the list items and displaying only the top 5 items. I want to add an option to display the bottom 5 items too. I have done that by creating a new class exactle the same as prev class with top array replaced by bottom array.

Upvotes: 0

Views: 806

Answers (4)

MarkG
MarkG

Reputation: 541

The ArrayAdapter class has a built-in method for sorting via "sort (Comparator comparator)", provided you are willing to go to the trouble to write the Comparators that you need to do the sorting. I use this method to sort "in place", without having to re-load the adapter with an externally re-ordered list.

Check out http://developer.android.com/reference/android/widget/ArrayAdapter.html

and http://developer.android.com/reference/java/util/Comparator.html

Upvotes: 0

Huang
Huang

Reputation: 4842

Umang, I don't have eclipse on hand now and I just want to express my train of thought to solve your problem. Please write the codes yourself and test it.

  1. There must be an adapter associated with your listview, inside it, you can set a variable to moniter the order mode, like: private int mode;
  2. Inside the getView() method of the adapter, based on the mode, return the items as you want. I think you have finished the steps above, since you can change the order already.
  3. In the first Activity, you can set some event for the user to chage the order, i.e, via the Menu. So you override public boolean onCreateOptionsMenu (Menu menu).
  4. In the corresponding public boolean onOptionsItemSelected (MenuItem item), you set the mode value based on the item index the user selected.
  5. Call adapter.notifyDataSetChanged() to notify the system that the data for the listView has been changed.
  6. call listView.invalidate() to show the new ListView.

Upvotes: 0

Rajdeep Dua
Rajdeep Dua

Reputation: 11230

You can re-sort the underlying data structure before setting it in the adapter.

Upvotes: 1

Arnab Chakraborty
Arnab Chakraborty

Reputation: 7472

Usually a list is displayed using a ListView. ListViews usually have an adapter associated with them. The Views are listed in the order they exist in the adapter. So to change the order of elements in the list , all you have to do is set a new adapter to it where the the elements are ordered as you wish (You could also try to change of the order of elements of the existing adapter, but I don't know if it can be done).

You can see the ListView Hello World Example to have a better understanding of ListViews.

Upvotes: 0

Related Questions