Search code examples
androidlistviewandroid-arrayadapterrunnable

Is it possible to create a ListView using run()?


I would like to know if it is possible to create a list view in runnable using something like this ? Could someone please give me an example to do it? Thank you.

public void testBtnListViewClick(View v) {
    MainActivity.this.runOnUiThread(new Runnable() {

     @Override
    public void run() {
       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() {

            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);
        ll.addView(lv, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        setContentView(ll);
   }
}

Solution

  • Yes ..you can..runOnUiThread() which runs in the main thread.In android UI changes like Views can be modiied or added only in UI thread..Its in the UI thread so no problem for yours..

    inside that this refers to runnable object..so change these lines

    LinearLayout ll = new LinearLayout(this);
    ListView lv = new ListView(this);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, values);
    

    into

    LinearLayout ll = new LinearLayout(MainActivity.this);
    ListView lv = new ListView(MainActivity.this);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.list_item, values);