Android beginner here. I was playing around with ListViews, trying to create them dynamically instead of the 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) {
//Toast.makeText(getBaseContext(), ""+arg2, Toast.LENGTH_SHORT).show();
Log.d("DEBUG", ""+arg2);
}
});
ll.addView(lv);
setContentView(ll);
}
}
Basically I first create a LinearLayout object and then make a ListView object as one of its child. I observed that the list items so created are not clickable. But if I write
setContentView(lv);
instead of
setContentView(ll);
the list items are clickable. Can anyone please explain this? How do I make the list items clickable if I have to implement my class the latter way? I don't want to go the ListActivity way.
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>