Creating a ListView Programmatically

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) {
            //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 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>
+5
source share
2 answers

change your code:

ll.addView(lv);

:

ll.addView(lv, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

, , - , .

+6

, LinearLayout XML, , , , . , , LinearLayout , , - ListView , IMHO.

public class ExampleActivity extends Activity implements OnItemClickListener {

private LinearLayout ll;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    ll = (LinearLayout) findViewById(R.id.main_ll);
    ListView lv = new ListView(this);
    ll.addView(lv);

    String[] values = new String[10];
    for (int i = 0; i < 10; i++) {
        values[i] = "" + i;
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, values);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    Toast.makeText(this, "" + arg2, Toast.LENGTH_SHORT).show();
    Log.d("DEBUG", "" + arg2);
}

}

+2

All Articles