【Android -- UI】TextView

124 阅读1分钟

1.1 概念

  • 文本的字体尺寸单位为sp :
  • sp: scaled pixels(放大像素). 主要用于字体显示。
创建方式
  • 在 XML 文件中通过属性 android:text 设置文本
  • 在 Java 代码中调用文本视图对象的 setText 方法设置文本
引用字符串资源
  • 在XML文件中引用(@string/xxx)
  • 在Java代码中引用(R.string.xxx)

1.2 常用属性

1.3 带图片(drawableXxx)的TextView

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  tools:context="com.jay.example.test.MainActivity">  
  <TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:drawableTop="@drawable/show1" 
    android:drawableLeft="@drawable/show1" 
    android:drawableRight="@drawable/show1" 
    android:drawableBottom="@drawable/show1" 
    android:drawablePadding="10dp" 
    android:text="张全蛋"/> 

 </RelativeLayout>

1.4 设置字体

  • layout中设置字体
<!-- sans字体 -->
<TextView
    android:text="Hello,World"
    android:typeface="sans" />

<!-- serifs字体 -->
<TextView
    android:text="Hello,World"
    android:typeface="serif" />

<!-- monospace字体 -->
<TextView
    android:text="Hello,World"
    android:typeface="monospace" />  
  • 代码中使用字体

需要引入ttf字体文件。把字体文件放在assets/font目录里。 代码中使用AssetManager来获取字体-->

tv.setTypeface(Typeface.SERIF);
tv.setTypeface(Typeface.SANS_SERIF);
tv.setTypeface(Typeface.MONOSPACE);


// 引入字体库
TextView tv1 = findViewById(R.id.tv1);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/otherFont.ttf");
 // 使用字体 
tv1.setTypeface(tf);