Getting height of text view before rendering to layout

后端 未结 5 1375
鱼传尺愫
鱼传尺愫 2020-12-02 08:23

Could not find any good solution calculating textview height where text was set before rendering textview to layout. Any help please

5条回答
  •  被撕碎了的回忆
    2020-12-02 09:07

    Good answer from @support_ms, but I'm not sure of the point of creating a new TextView and working out all of this input params when you could just format your TextView first and then call the static method with just one parameter, the TextView itself!

    Also I'm not sure why one parameter was labelled deviceWidth I just use the width of the Textview itself. Mine was match_parent and I suppose any TextView with wrap_content may not work at all. But that's what you get.

    public static int getHeight(TextView t) {
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(screenWidth(t.getContext()), View.MeasureSpec.AT_MOST);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        t.measure(widthMeasureSpec, heightMeasureSpec);
        return t.getMeasuredHeight();
    }
    
    public static int screenWidth(Context context)
    {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        return display.getWidth();
    }
    

提交回复
热议问题