What's the quickest way to add several views to a LinearLayout?

后端 未结 3 1142
醉酒成梦
醉酒成梦 2021-02-02 14:56

I have a LinearLayout view that already contains several elements. I want to add a lot more Views to it, programmatically. And because this is inside a Scroll

3条回答
  •  Happy的楠姐
    2021-02-02 15:28

    Just use a ListView!

    It's the easiest to set up and easiest to maintain. You define an XML layout for the List-Row, and an XML layout for the View which holds the entire List. The ListAdapter does the rest for you.

    Just create a:

    List> services = new ArrayList>();
    

    ...and loop through your data to add as many items as you like to the Map. Then set this map to your ListAdapter. Whether 10 items or 100 items the ListAdapter will create a List with that many items.

    Example:

        public void updateProductList(String searchTerm) {
            createOrOpenDB(this);
            Cursor cursor = (searchTerm!=null)? dbAdapter.fetchWhere(TBL_NAME, KEY_NAME+" LIKE '%"+searchTerm+"%'")
                    : dbAdapter.fetchAll(TBL_NAME);
            int rows = cursor.getCount();
            if (rows<=0) return;
            services.clear(); //clear current list
            for (int i=0; i map = new HashMap();
                cursor.moveToPosition(i);
                map.put(KEY_NAME, "" + cursor.getString(cursor.getColumnIndex(KEY_NAME)));
                map.put(KEY_DESC, "" + cursor.getString(cursor.getColumnIndex(KEY_DESC)));
                map.put(KEY_COST, "" + cursor.getDouble(cursor.getColumnIndex(KEY_COST)));
                services.add(map);
            }
            cursor.close();
            closeDB();
    
            ListAdapter adapter = new SimpleAdapter(this, services, R.layout.products_view_row,
                    new String[] {KEY_NAME, KEY_DESC, KEY_COST},
                    new int[] {R.id.listViewText1, R.id.listViewText2, R.id.listViewText3});
            setListAdapter(adapter);
        }
    

提交回复
热议问题