文本视图返回错误的文本大小 [英] Text view returning wrong text size

查看:25
本文介绍了文本视图返回错误的文本大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取文本视图的文本大小,以便在用户按下按钮时增加文本大小,这表明它有助于增加文本视图中的文本大小.让我清楚我到目前为止所做的

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

我有一个文本视图并通过 dimen 文件夹设置其文本大小

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

32sp

所以对于平板电脑等大型设备是 32sp.

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

但是当我通过 java 获取文本视图的大小时,它返回错误的文本大小.在这里见波纹管我得到了文本大小

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();

但这让我返回了错误的 textview 文本大小.

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

请给我建议,我怎样才能获得文本视图中显示的确切文本大小.因为我想在按下按钮时增加文本大小,所以为此我需要检索文本的实际大小,即如果文本大小为 32,我想将其增加 32+1 = 3sp

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

但是当我检索文本大小时,它是其他一些东西,例如对于平板电脑,我已将其设置为 32sp,但它正在检索我 42,因此在 42+1 中进行增量使其为 43,当我将其设置为按钮时,按下它的外观尴尬的.

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. ??

推荐答案

问题在于 getTextSize() 返回以像素为单位的大小,而不是以 sp 为单位的.所以你可以先将像素转换为 sp 然后 -

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);

要将像素转换为 sp 使用此 -

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;
}

代码取自此处.

这篇关于文本视图返回错误的文本大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆