您当前的位置:首页 > Android教程

Android开发学习教程(6)- 基本控件TextView用法和属性

时间:2022-01-02 08:20:35 阅读数:10,589人阅读
版权声明:转载请注明出处,谢谢!
—— 世界上只有一种真正的英雄主义,就是认清了生活的真相后,还依然热爱它。

TextView是什么

TextView文本标签,常用来显示文字的一个控件,比如第二篇章的Hello World和上一篇章中的Hello Activity。

TextView有什么用

常用来显示文字。

TextView的使用

以上一篇章中的Hello Activity为例,我们来看看TextView的用法:

	<?xml version="1.0" encoding="utf-8"?>
	<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
		xmlns:app="http://schemas.android.com/apk/res-auto"
		xmlns:tools="http://schemas.android.com/tools"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		tools:context=".TestActivity">

		<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Hello Activity"
		app:layout_constraintBottom_toBottomOf="parent"
		app:layout_constraintLeft_toLeftOf="parent"
		app:layout_constraintRight_toRightOf="parent"
		app:layout_constraintTop_toTopOf="parent" />
	</androidx.constraintlayout.widget.ConstraintLayout>

上一篇章中我们没有细讲TextView的属性,现在我们详细来看。

	android:id:控件的唯一标识ID;
	android:text:要显示的文字内容;
	android:layout_width:TextView的宽度(或者说长度),值为wrap_content意思是自适应宽度,就是文字有多长,TextView的宽度就有多长;
	android:layout_width:TextView的高度,值为wrap_content意思是自适应高度,就是文字有多高,TextView的高度就有多高;
	app:layout_constraintBottom_toBottomOf="parent":表示TextView的底部与父类控件(也就是ConstraintLayout)的底部对齐;
	app:layout_constraintEnd_toEndOf="parent":表示TextView的右边与父类控件(也就是ConstraintLayout)的右边对齐;
	app:layout_constraintStart_toStartOf="parent":表示TextView的左边与父类控件(也就是ConstraintLayout)的左边对齐;
	app:layout_constraintTop_toTopOf="parent":表示TextView的顶部与父类控件(也就是ConstraintLayout)的顶部对齐;

以上这三个与父类对齐的属性读起来挺绕口的,但是在Android Studio的UI编辑器中看起来就一目了然其实就是屏幕居中了,如下:(这里如果实在不明白也没关系,我们后面章节会着重讲常用布局)

继续看TextView常用属性

	android:textColor="#FF0000" 文字的颜色为红色
	android:textSize="20sp" 文字的大小为20sp
	android:background="#cccccc" TextView的背景颜色为灰色
	android:singleLine="true" TextView的内容只显示一行,超出部分显示省略号…

我们来试试上面的属性

	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Hello Activity Hello Activity Hello Activity Hello Activity"
		android:textColor="#FF0000"
		android:textSize="20sp"
		android:background="#cccccc"
		android:singleLine="true"
		app:layout_constraintBottom_toBottomOf="parent"
		app:layout_constraintEnd_toEndOf="parent"
		app:layout_constraintStart_toStartOf="parent"
		app:layout_constraintTop_toTopOf="parent"/>

本篇源码下载地址:https://pan.baidu.com/s/1oK46p3K8aRptXJYjpIT3VQ 提取码: helu

------转载请注明出处,感谢您对原创作者的支持------

有偿提供技术支持、Bug修复、项目外包、毕业设计、大小作业

Android学习小站

Q Q:1095817610

微信:jx-helu

邮箱:1095817610@qq.com

添加请备注"Android学习小站"