wrap_content for a listview's width

后端 未结 2 901
清酒与你
清酒与你 2020-12-05 19:36

Is there a way to have a ListView with the with equal to the longest row? Setting wrap_content for the ListView \'s width has no effect. The ListView covers the whole screen

2条回答
  •  庸人自扰
    2020-12-05 19:56

    Sometimes, you know there will always be a limited number of items, maybe 5, maybe 40. In those times you still want to use a ListView and you still want to wrap content.

    For those times there is this method:

    /**
     * Computes the widest view in an adapter, best used when you need to wrap_content on a ListView, please be careful
     * and don't use it on an adapter that is extremely numerous in items or it will take a long time.
     *
     * @param context Some context
     * @param adapter The adapter to process
     * @return The pixel width of the widest View
     */
    public static int getWidestView(Context context, Adapter adapter) {
        int maxWidth = 0;
        View view = null;
        FrameLayout fakeParent = new FrameLayout(context);
        for (int i=0, count=adapter.getCount(); i maxWidth) {
                maxWidth = width;
            }
        }
        return maxWidth;
    }
    

    Use it like so (notice I added some extra space to the width just in case):

    listView.getLayoutParams().width = getWidestView(mContext, adapter)*1.05;
    

提交回复
热议问题