init ListView from ArrayAdapter - Android User Interface

Android examples for User Interface:ListView

Description

init ListView from ArrayAdapter

Demo Code


//package com.java2s;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Main {
    public static void initListView(Context context, ListView listView,
            String prefix, int numItems, int layout) {
        // By using setAdpater method in listview we an add string array in list.
        String[] arr = new String[numItems];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = prefix + (i + 1);/*from   ww  w.j  a va  2s  .  c o  m*/
        }
        listView.setAdapter(new ArrayAdapter<String>(context, layout, arr));
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                //Context context = view.getContext();
                String msg = "item[" + position + "]="
                        + parent.getItemAtPosition(position);
                //Toast.makeText(context, msg, 1000).show();
                System.out.println(msg);
            }
        });
    }
}

Related Tutorials