[Android]TextView设置字体大小时应该知道的事-同样的textSize不同的效果

在学helloworld的时候就第一个接触的控件就是TextView,这个是非常常用的一个文本控件,现在我们要说的就是关于设置大小时应该清楚的一两个问题.下面这个案例来说明.

先看xml中的案例:

<LinearLayout
        
        android:layout_below="@+id/main_button_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textview_1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:text="字体20sp" />
        
        <TextView
            android:id="@+id/textview_2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:text="字体20px" />
    </LinearLayout>
效果图:


好了,看效果图就知道本博文主要讲的就是sp和px的一个不清楚的情况下 出现 大小不如所愿的问题.

代码案例:

1.dimens.xml

 <dimen name="text_size_20">20sp</dimen>
2.在java中出现大小不一样的问题的原型:

		TextView textView1 = (TextView) findViewById(R.id.textview_1);
		textView1.setTextSize(20);//默认单位其实是sp
		
		TextView textView2 = (TextView) findViewById(R.id.textview_2);
		float size = this.getResources().getDimension(R.dimen.text_size_20);
		Log.d(TAG, "textSize = "+size); //30
		textView2.setTextSize(size); //这里的size单位是px,即30个像素 
		
3.看看TextView中的setTextSize方法 就能看出问题了.

怎么改,现在你应该知道了吧?

在后面追加修改成:

textView2.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);

Ok,这里其实是基础的东西.单位分清楚其实也很重要哦.大笑


发布了70 篇原创文章 · 获赞 36 · 访问量 22万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章