ListView in ScrollView - small bug

前端 未结 2 1163
广开言路
广开言路 2021-01-26 06:27

I\'d like to have a listview in scrollview. This method is doing it almost perfect: https://stackoverflow.com/a/3495908/2811653

There is a bug when I enter more text in

2条回答
  •  [愿得一人]
    2021-01-26 07:17

    Try this solution that I posted here.

    If you do not want the ListView itself to scroll and just want the ListView's height to be such that all elements are shown, then you can create a subclass of ListView to accomplish this.

    public class ListViewForEmbeddingInScrollView extends ListView {
        public ListViewForEmbeddingInScrollView(Context context) {
            super(context);
        }
    
        public ListViewForEmbeddingInScrollView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public ListViewForEmbeddingInScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 4, MeasureSpec.AT_MOST));
        }
    }
    

    Manipulating the heightMeasureSpec to be AT_MOST with a very large size (Integer.MAX_VALUE >> 4) causes the ListView to measure all of its children up to the given (very large) height and set its height accordingly.

    There is much discussion about this problem here including a lot of discussion as to whether or not is is appropriate to even do this. I don't have enough reputation to post my answer there but this is better than any of the solutions in that link. Perhaps someone with more reputation will run across this and post a solution on that other question that links back to this one.

提交回复
热议问题