How to set a maximum height with wrap content in android?

前端 未结 7 2342
你的背包
你的背包 2020-12-09 02:01

In android, how can you create a scroll view that\'s got a max height, and wrap contents, basically it wraps the content vertically, but has a maximum height?

I trie

7条回答
  •  一生所求
    2020-12-09 02:39

    1.) Create a class to handle setting maximum height to what is passed by the user:

    public class OnViewGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
    
    
    private Context context;
    private int maxHeight;
    private View view;
    
    public OnViewGlobalLayoutListener(View view, int maxHeight, Context context) {
        this.context = context;
        this.view = view;
        this.maxHeight = dpToPx(maxHeight);
    }
    
    @Override
    public void onGlobalLayout() {
        if (view.getHeight() > maxHeight) {
            ViewGroup.LayoutParams params = view.getLayoutParams();
            params.height = maxHeight;
            view.setLayoutParams(params);
        }
    }
    
    public int pxToDp(int px) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return dp;
    }
    
    public int dpToPx(int dp) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }
    }
    

    2.) Attach this to the view and pass the maximum height in DP:

    messageBody.getViewTreeObserver()
                .addOnGlobalLayoutListener(
                 new OnViewGlobalLayoutListener(messageBody, 256, context)
                 );
    

    Thanks to @harmashalex for the inspiration. I made modifications to as setting the layout params didn't work by @harma's code. Also, dp-to-px conversion is necessary to offload wondering about it.

提交回复
热议问题