[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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章