Hi, guys! Sorry for long time, didn't update my blog because recently are busy with my personal stuff. In this tutorial, we will learn how to sort the list by ascending or descending order. This able to done by using sort() method and comparator class.
1. Sort Method
Ascending Order
By referring tutorial 9, we are creating a list view layout and put some elements in an array. Now we would like to modify the previous project in order to sort the them in ascending order. Use the Arrays.sort(items) command to sort them as shown in Figure 12.1.
public class ListMonth extends ListActivity {
static final String[] MONTHS = new String[] { "January", "February",
"March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Arrays.sort(MONTHS);
setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_list
_month, MONTHS));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
static final String[] MONTHS = new String[] { "January", "February",
"March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Arrays.sort(MONTHS);
setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_list
_month, MONTHS));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
Figure 12.1