Is it even possible to create a ListActivity completely during runtime without using XML? I’m trying to create a list view with 8 items, alternating between four TextViews and four ToggleButtons. The goal is to have a vertical list with TextView, ToggleButton, TextView, ToggleButton, TextView, ToggleButton, TextView, ToggleButton
Here’s my code:
public class MyActivity extends ListActivity implements OnCheckedChangeListener
{
private ViewGroup.LayoutParams widthLayout = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT );
private TextView[] textItems = new TextView[ 4 ];
private ToggleButton[] toggleButtons = new ToggleButtons[ 4 ];
private static final int ID_BASE = 5550; // unique ID for this activity
public void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setupView();
}
//
private void setupView() {
Vector v_itemList = new Vector();
for ( int i=0; i < 4; i++ ) {
int t_color = 0xFFFFFF;
//
textItems[i] = new TextView( this );
textItems[i].setText( ""+i+". text line" );
textItems[i].setColor( t_color );
t_color -= 0x220022;
//
toggleButtons[i] = new ToggleButton( this );
toggleButtons[i].setTextOff( ""+i+". Off" );
toggleButtons[i].setTextOn( "On ("+i+")" );
toggleButtons[i].setId( ID_BASE+i );
toggleButtons[i].setChecked( i%2 == 1 ? true : false );
toggleButtons[i].setOnCheckedChangeListener( this );
//
v_itemList.addElement( textItems[i] );
v_itemList.addElement( toggleButtons[i] );
}
ArrayAdapter listItemAdapter = new ArrayAdapter( this, android.R.layout.simple_list_item_1, v_itemList );
this.setListAdapter( listItemAdapter );
}
}
When I've tried this code, I get a list list view of all the element's toString() output: android.widget.TextView@4376f760 android.widget.ToggleButton@437708c8 android.widget.TextView@43772b10 android.widget.ToggleButton@43772fa0 ... ect ...
I then tried to add the TextView and ToggleButton using:
this.addContentView( textItems[i], widthLayout );
this.addContentView( toggleButtons[i], widthLayout );
within the for loop. But recieved a RuntimeException, Your content must have a ListView whos id attribute is 'android.R.id.list'
Any help would be appreciated, and if possible I'd like to avoid using any reference to XML.
That's not how you use an ArrayAdapter. The array you give it should be the data to be displayed, not the views to display the data. Normally, you only get TextViews out of an ArrayAdapter. To get your ToggleButtons, you will need to subclass ArrayAdapter and override getView().
The strings you are seeing is because the ArrayAdapter is treating your array of views as the data to be displayed. The standard behavior for ArrayAdapter is:
See the documentation for ArrayAdapter and the List View Tutorial for more info.
I'm curious why you want to put toggle buttons in a ListView. What you are describing sounds like it would be better suited to a LinearLayout.