Auto Scale TextView Text to Fit within Bounds

后端 未结 30 2877
囚心锁ツ
囚心锁ツ 2020-11-21 05:49

I\'m looking for an optimal way to resize wrapping text in a TextView so that it will fit within its getHeight and getWidth bounds. I\'m not simply looking for

30条回答
  •  不思量自难忘°
    2020-11-21 06:13

    My method is:

    public void changeTextSize(int initialSize, TextView tv) {
    
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        double width = displayMetrics.widthPixels / displayMetrics.xdpi;
        double height = displayMetrics.heightPixels / displayMetrics.ydpi;
    
        Log.i("LOG", "The width of the tested emulator is: " + width);
        Log.i("LOG", "The height of the tested emulator is: " + height);
    
        double scale = Math.min(width / 2.25, height / 4.0); //See the logcat >>> width = 2.25 and heigt = 4.0
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, (int) (initialSize * scale));
    
    }
    

    For example:

    changeTextSize(16, findViewById(R.id.myTextView));
    changeTextSize(12, findViewById(R.id.myEditText));
    

提交回复
热议问题