스터디/Android+Java

Android TextView Auto Size - ResizeView (2012.05.24)

Dalmangyi 2017. 10. 7.

안드로이드에선 TextView에 출력되는 글자의 사이즈가 할당된 영역에 맞게 자동으로 폰트가 늘어나거나 줄어드는 기능이 없다.

그래서 LinearLayout을 Custom에서 ResizeView가 만들어졌다.

ResizeView는 내부에 존재하는 TextView의 폰트 사이즈를 변경해준다.





public class ResizeView extends LinearLayout {


    public ResizeView(Context context, AttributeSet attrs) {

        super(context, attrs);

    }


    public ResizeView(Context context) {

        super(context);

    }


    @Override

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        super.onLayout(changed, left, top, right, bottom);


        // oldWidth used as a fixed width when measuring the size of the text

        // view at different font sizes

        final int oldWidth = getMeasuredWidth() - getPaddingBottom() - getPaddingTop();

        final int oldHeight = getMeasuredHeight() - getPaddingLeft() - getPaddingRight();


        // Assume we only have one child and it is the text view to scale

        TextView textView = (TextView) getChildAt(0);


        // This is the maximum font size... we iterate down from this

        // I've specified the sizes in pixels, but sp can be used, just modify

        // the call to setTextSize


        float size = getResources().getDimensionPixelSize(R.dimen.solutions_view_max_font_size);


        for (int textViewHeight = Integer.MAX_VALUE; textViewHeight > oldHeight; size -= 0.1f) {

            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);


            // measure the text views size using a fixed width and an

            // unspecified height - the unspecified height means measure

            // returns the textviews ideal height

            textView.measure(MeasureSpec.makeMeasureSpec(oldWidth, MeasureSpec.EXACTLY), MeasureSpec.UNSPECIFIED);


            textViewHeight = textView.getMeasuredHeight();

        }

    }

}





<커스텀뷰>



커스텀뷰인 ResizeView클래스에서는 자신의 하위 자식 노드인 textView에 대해서 TextSize를 정해주고 있다.

R.dimen.solutions_view_max_font_size 라는 처음보는 녀석이 있었는데 솔직히 어떻게 설정값을 줘야 될지 몰라서 일단은 TextView사이즈중 크다고 생각되는 72pt를 값으로 주어줬다.


res/values/dimen.xml 안에는

<resources>

<dimen name="solutions_view_max_font_size">72pt</dimen>

</resources>

이렇게 작성하였다.



커스텀뷰를 적용하고 싶은 곳(xml)에

<com.custom.ResizeView
   
android:layout_width="fill_parent"
   
android:layout_height="0dp"
   
android:layout_margin="10dp"
   
android:layout_weight="1"
   
android:orientation="horizontal" >

    <TextView
        android:id="@+id/CustomTextView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
</com.custom.ResizeView>

요로코롬 적어주면 된다.

하지만 여기서 주의 할 것은 자식 노드로 있는 TextView태그 안에 속성값으로 

android:textSize를 정해주게 되면 화면 초기 로드시에 정해준 크기로 변했다가 곧 ResizeView인 부모 노드의 사이즈 만큼 변하게 된다.

아주 빠른 폰에선 상관없겠지만 왠만한 모든 폰은 느리다고 가정해서.. 처음에 꿈틀 거리는 현상은

보기 안좋으니 꼭 유의하시기 바랍니다.



댓글