【问题标题】:Android - Making textview auto resizable text to fit layoutAndroid - 使 textview 自动调整大小的文本以适应布局
【发布时间】:2017-03-23 18:16:34
【问题描述】:

我正在尝试获取 textview 中文本的大小,以便稍后在代码中使用它。

我已经声明了一个浮点数和我的文本视图

private float mStartTextSize;
private TextView mWordTextView;

然后在我的 onCreate 我有

 mWordTextView = (TextView) findViewById(R.id.factTextView);
 mStartTextSize = mWordTextView.getTextSize();

但是当我调试和使用我的手机时,即使我在 xml 中将它设置为 30sp,它也会得到 105 的值。

 <TextView
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:text="@string/choose_teams"
    android:singleLine="false"
    android:id="@+id/wordTextView"
    android:textSize="30sp"
    android:textColor="@android:color/white"
    android:textStyle="bold|italic"
    android:layout_below="@+id/titleTextView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="70dp"
    android:gravity="top|center"/>

【问题讨论】:

  • 谢谢!我很感激。

标签: android resize textview text-size


【解决方案1】:

您收到的尺寸是像素而不是 sp。

getTextSize
float getTextSize ()

Returns
float   the size (in pixels) of the default text size in this TextView.

getTextSize() documentation

您可以使用它来将 sp/dp 转换为像素并返回,而无需上下文。

public static float pxToDp(int px) {
    return px / Resources.getSystem().getDisplayMetrics().density;
}

public static float dpToPx(int dp) {
    return dp * Resources.getSystem().getDisplayMetrics().density;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多