Text view returning wrong text size

别说谁变了你拦得住时间么 提交于 2019-12-12 18:34:27

问题


I need to get the text size of the text view so that I would increment in text size while user pressing the button which indicates that it helps in increasing the text size in the text view. Let me clear what I have done so far

i have a text view and setting its text size through dimen folder

 <TextView
            android:id="@+id/tv_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="2dp"
            android:text="@string/flash"
            android:textSize="@dimen/tv_text_fontsize"
            android:gravity="fill_horizontal"
            />

to support my text view text size to all screen sizes accordingly I have made diferent dimen folder and setting the text size as follows

<dimen name="tv_text_fontsize">32sp</dimen>

So it is 32sp for large devices such as tablets.

But When I get the size of text view through java it returns me wrong text size. here see bellow Ho I am getting the text size

float textSize = tvContentString.getTextSize();

but this is returning me wrong text size of the textview .

Please suggest me , how can I get the exact text size being displayed in the text view. As because I want to increment in text size on button press so for this I need to retrieve the actual size of text i.e if the text size is 32 I want to increment it 32+1 = 3sp

But when I retrieve the text size it is some thing else such as for tablets I have set it 32sp but it is retrieving me 42 so making increment in 42+1 making its 43 and when I set it on button press its look awkward.

Please help !!! How can I get real text size. ??


回答1:


The problem is that getTextSize() return the size in pixels, not in sp. So you can convert pixels to sp first then -

tvContentString.setTextSize(TypedValue.COMPLEX_UNIT_SP, new_size);

To convert from pixels to sp use this -

public static float pixelsToSp(Context context, float px) {
    float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
    return px/scaledDensity;
}

Code taken from here.



来源:https://stackoverflow.com/questions/35843043/text-view-returning-wrong-text-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!