Friday, March 4, 2011

ListActivity with two List

In this exercise, the ListView of a ListActivity switch between two ArrayAdapter.

ListActivity with two List

Note that notifyDataSetChanged() function of the new ArrayAdapter have to be called after setListAdapter(), to re-draw the List on screen.

package com.exercise.AndroidDualListActivity;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AndroidDualListActivity extends ListActivity{

String[] month = {
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};

String[] DayOfWeek = new String[] {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};

ArrayAdapter<String> monthAdapter, weekOfDayAdapter;
String strMonth, strDayOfWeek;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
monthAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, month);
weekOfDayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DayOfWeek);

setListAdapter(monthAdapter);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);

if(getListAdapter() == monthAdapter){
strMonth = (String)getListView().getItemAtPosition(position);
setListAdapter(weekOfDayAdapter);
weekOfDayAdapter.notifyDataSetChanged();
}else{
strDayOfWeek = (String)getListView().getItemAtPosition(position);
Toast.makeText(getBaseContext(), strMonth + ":" + strDayOfWeek, Toast.LENGTH_LONG).show();
setListAdapter(monthAdapter);
monthAdapter.notifyDataSetChanged();
}
}
}


Download the files.

2 comments:

Unknown said...

Dear Android-er

if i want to add icon on the left and arrow on the right. using this layout

The problem is,arrow not at right position but right after the list character.

Erik said...

hello rootd,

I think it's the problem on the layout of individual row, may be you can use RelativeLayout.