Android控件之TextView
可在程序中创建TextView对象
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv=new TextView(this);
tv.setText("酸菜鱼");
setContentView(tv);
}
运行图示如下
也可以在XML布局文件中使用TextView,为了便于以后的修改,大多数情况都要在布局文件中使用
TextView的常用属性很多,下面简单说几种呆会要用到的属性
android:autoLink设置是否当文本为URL链接/email/电话号码/map时,文本显示为可点击的链接。可选值(none/web/email/phone/map/all)
android:ellipsize设置当文字过长时,该控件该如何显示。有如下值设置:”start”—-省略号显示在开头;”end”——省略号显示在结尾;”middle”—-省略号显示在中间;”marquee”——以跑马灯的方式显示(动画横向移动)
android:marqueeRepeatLimit 在ellipsize指定为marquee的情况下,设定重复滚动次数,marquee_forever(无限次数)
android:SingleLine=true 文字是否一行显示
android:textColor设置文本颜色
android:textSize设置文字大小,推荐度量单位”sp”,如”15sp”
android:textStyle设置字形[bold(粗体) 0,italic(斜体) 1, bolditalic(又粗又斜) 2] 可以设置一个或多个,用“|”隔开
写一个如下的TextView控件,要求能识别超链接,字体为绿色,文字在一行以跑马灯的方式显示
<TextView
android:id="@+id/tv"
android:autoLink="all"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#00FF00"
android:focusable="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusableInTouchMode="true"
android:text="@string/hello_world"
/>
字符串在strings.xml中设置
<string name="hello_world">欢迎大家观看我的博客http://blog.csdn.net/suancaiyucoding
我的手机号:14878414521</string>
运行图示如下
也可以在程序中设置TextView的属性,如在程序中获得TextView的id,并设置字体的颜色
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv=(TextView)findViewById(R.id.tv);
tv.setText(Html.fromHtml("欢迎查看<font color=blue>酸菜鱼</font>的博客"));
}
运行图示如下