ListView Example

Package

android.widget.ListView

Layout

<ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Activity or Fragment

public class TestActivity extends Activity {
    private ListView mListView;
    private TestAdapter mAdapter;
    private List<UserInfo> mData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        mListView = (ListView)findViewById(R.id.list_view);

        mData = new ArrayList<UserInfo>();

        mAdapter = new TestAdapter(mData);
        mListView.setAdapter(mAdapter);
    }
    ...
}

TestAdapter

public class TestAdapter extends BaseAdapter{
    private List<UserInfo> mData;

    static class ViewHolder {
        public TextView text;
        public ImageView icon;
    }

    public TestAdapter(List<UserInfo> data) {
        mData = data;
    }

    @Override  
    public Object getItem(int position) {  
        return mData.get(position);  
    }  

    public int getCount() {
        return mData.size();
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext())
                               .inflate(R.layout.user_info, parent, false);

            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.text);
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.text.setText(mData[position].getUserName());
        holder.icon.setImageDrawable(mData[position].getUserPhoto());

        return convertView;
    }
}

Demo

Download

ListViewExample.zip