TextView-通过编程设置文本大小似乎不起作用

我正在使用 Eclipse 靛 o,在2个模拟器(2.2和3.0)上进行测试。

下面的代码显示了我现在正在测试的内容,但是当试图运行模拟器时,设置文本大小在屏幕上显示不出任何东西。(如果我注释掉文本大小,文本显示为红色)。我认为 Eclipse 并没有重新构建代码,但是我添加了一行代码来添加蓝色的背景,并且成功了。我试过在设置文本之后设置文本大小,但仍然没有成功。密码如下。谢谢你的帮助! (免责声明)-我试图远离 xml。因为我已经知道 Java 了,我不想再依赖它了。

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TextView;


public class TestAndroidvs2Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView text = new TextView(this);
text.setTextColor(Color.RED);
text.setTextSize(2);
text.setBackgroundColor(Color.BLUE);
text.setText("Hello Android");




setContentView(text);
}
}
231868 次浏览

请参阅 这个链接了解更多关于设置代码文本大小的信息。基本上它说:

Public void setTextSize (int 单位,浮点大小)

将默认文本大小设置为给定的单元,然后 有关可能的维度单位,请参见 TypedValue 类型价值 属性

TextSize 参数

所需尺寸单位。
给定单位中所需的大小。

文本大小2几乎是不可见的。至少有14个。顺便说一句,使用 xml 有很多优点,一旦您需要做比“ Hello World”更复杂的事情时,它将使您的生活更轻松。

方法 TextView.setTextSize(int unit , float size);接受两个参数。

试试这个:

text.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);

请参阅 这个这个

更新: 现在,setTextSize(float size)将设置文本大小 自然而然地在“ scaled pixel”单位。不需要提到 COMPLEX _ UNIT _ SP 手动。 请参阅 文件

在我的案例中使用了这个 方法:

public static float pxFromDp(float dp, Context mContext) {
return dp * mContext.getResources().getDisplayMetrics().density;
}

这里设置 TextView 的 TextSize 程序化:

textView.setTextSize(pxFromDp(18, YourActivity.this));

继续享受:)

这为我解决了问题。 所有设备的字体大小都一样。

 textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimension(R.dimen.font));

目前,setTextSize(float size)方法将 工作顺利,所以我们 不需要使用其他方法为改变文本大小

Java 源代码

/**
* Set the default text size to the given value, interpreted as "scaled
* pixel" units.  This size is adjusted based on the current density and
* user font size preference.
*
* <p>Note: if this TextView has the auto-size feature enabled than this function is no-op.
*
* @param size The scaled pixel size.
*
* @attr ref android.R.styleable#TextView_textSize
*/
@android.view.RemotableViewMethod
public void setTextSize(float size) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}

示例使用

textView.setTextSize(20); // set your text size = 20sp

在 Kotlin,你可以像这样简单地使用,

textview.textSize = 20f

对我来说,直到我禁用了自动文本大小调整:

if (Build.VERSION.SDK_INT >= 26) {
textView.setAutoSizeTextTypeWithDefaults(TextView.AUTO_SIZE_TEXT_TYPE_NONE)
}
setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeInSp)

可以使用 setTextSize方法设置文本大小。

TextView.setTextsize(12);