Android dynamically created table - bad performance

♀尐吖头ヾ 提交于 2019-12-04 12:25:09

Android is very slow at having many Views in memory. To work around this I would recommend using the default Andoird ListView with a custom ListAdapter.

The Views are created on the fly when the user scrolls the list, so only the currently visible Views have to be in memory.

This example uses a CursorAdapter, but you can also use an ArrayAdapter.

private class ExtendCursorAdapter extends CursorAdapter {

    public ExtendCursorAdapter(Context context, Cursor c) {
        super(context, c);
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) { //Determine if it's a category or an item
            return 0; // category
        } else {
            return 1; // item
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (getItemViewType(position) == 0) {
            View v;
            if (convertView != null)
                v = convertView;
            else
                v = inflater.inflate(R.id.listcategory);
            // Set title, ...
            return v;
        } else{
            // the same for the item
        }
    }
}

An additional performance increase comes from the usage of convertView. While scrolling you don't need to create any additional Views because Android reuses the ones which come out of sight. You just have to make sure to reset all data of convertView.

Johnson Wong

I ran into similar performance problems, except all I wanted to do was display text in a formatted table shape (columns auto-sized etc). In this case, you may want to forego TableLayout entirely and use something like java.util.Formatter to transform text into a table shape and feed this to a single TextView. For me, this resulted in large performance gains (~2 seconds to load an activity down to almost instant).

See more detials here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!