Populate listview from arraylist of objects

前端 未结 2 1031
滥情空心
滥情空心 2020-12-05 10:34

I have a listactivity which will display a list of persons name and address with data from arraylist of objects. here\'s the method to fill the listview so far..

<         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 10:55

    This is my solution to the custom list adapter problem. First a custom arrayadapter:

    public class MemoListAdapter extends ArrayAdapter {
    
    private int layoutResourceId;
    
    private static final String LOG_TAG = "MemoListAdapter";
    
    public MemoListAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
        layoutResourceId = textViewResourceId;
    }
    
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            MemoEntry item = getItem(position);
            View v = null;
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
                v = inflater.inflate(layoutResourceId, null);
    
            } else {
                v = convertView;
            }
    
            TextView header = (TextView) v.findViewById(R.id.list_memo_item_header);
            TextView description = (TextView) v.findViewById(R.id.list_memo_item_text);
    
            header.setText(item.getHeader());
            description.setText(item.getValue());
    
            return v;
        } catch (Exception ex) {
            Log.e(LOG_TAG, "error", ex);
            return null;
        }
    }
    

    }

    and in the onCreate method of the activity:

    adapter = new MemoListAdapter(this, R.layout.list_memo_item_layout); // the adapter is a member field in the activity
    setContentView(R.layout.activity_view_memo_layout);
    ListView lv = (ListView) findViewById(R.id.view_memo_memo_list);
    lv.setAdapter(adapter);
    

    and then i fill the adapter after some fetching with a call like this:

    ArrayList memoList = new ArrayList(); //here you should use a list with some content in it
    adapter.addAll(memoList);
    

    So to adapt this to your solution, create your own customadapter, and instead of my object MemoEntry, use your Person class. In the getView method, change it to suit your needs. It's about the same as what i'm doing so shouldn't be too hard.

    Hope this helps you a bit!

提交回复
热议问题