我正在使用Eclipse Indigo,在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);
}
}
Run Code Online (Sandbox Code Playgroud)
Hou*_*ine 480
该方法TextView.setTextSize(int unit , float size);有两个参数.
试试这个 :
text.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
Run Code Online (Sandbox Code Playgroud)
Vik*_*kas 67
这为我解决了这个问题.我在所有设备上都有统一的字体大小.
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimension(R.dimen.font));
Run Code Online (Sandbox Code Playgroud)
Pha*_*inh 23
目前,setTextSize(float size)方法将运行良好,因此我们不需要使用另一种方法来更改文本大小
android.widget.TextView.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);
}
Run Code Online (Sandbox Code Playgroud)
使用示例
textView.setTextSize(20); // set your text size = 20sp
Run Code Online (Sandbox Code Playgroud)
Jac*_*ack 12
有关在代码中设置文本大小的详细信息,请参阅此链接.基本上它说:
public void setTextSize(int unit,float size)
从以下版本开始:API Level 1将默认文本大小设置为给定的单位和值.有关可能的尺寸单位,请参见TypedValue.相关的XML属性
android:textSize参数
unit所需的尺寸单位.
size给定单位中的所需大小.
在我的情况下使用此方法:
public static float pxFromDp(float dp, Context mContext) {
return dp * mContext.getResources().getDisplayMetrics().density;
}
Run Code Online (Sandbox Code Playgroud)
这里以编程方式设置TextView的TextSize:
textView.setTextSize(pxFromDp(18, YourActivity.this));
Run Code Online (Sandbox Code Playgroud)
继续享受:)
| 归档时间: |
|
| 查看次数: |
167148 次 |
| 最近记录: |