Android newbie here. I played with ListViews, trying to create them dynamically instead of an XML file. I observe the following odd behavior in my code.
public class SettingsHolder extends Activity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ListView lv = new ListView(this);
String[] values = new String[10];
for(int i=0;i<10;i++){
values[i] = ""+i;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, values);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Log.d("DEBUG", ""+arg2);
}
});
ll.addView(lv);
setContentView(ll);
}
}
Basically, I first create a LinearLayout object, and then create a ListView object as one of its children. I noticed that the list items created in this way are not interactive. But if I write
setContentView(lv);
instead
setContentView(ll);
list items can be clicked. Can anyone explain this? How to make list items available if I need to implement my class last? I do not want to go to ListActivity.
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
source
share