持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情
今天我们来看Android 中最最基本的一个UI控件,TextView(文本框)由于我之前是做前端的,所以我看到这个组件的时候 第一反应这不就是给 < p > 嘛。接下来看见TextView 的属性,一股熟悉的味道扑面而来。心想那这块上手应该很快了,那么让来我们来看一下具体的使用方法。
TextView 基本属性
首先让我们来先写一个 TextView。 还是回到我们上次创建的mytest 项目中来,找到app -> src -> main -> res -> layout 目录下,我们可以看到有一个activity_main.xml的文件。双击打开,我们一般会看到一个这样的页面。
是不是一股熟悉的味道,像不像网页三剑客中的Dreamweaver。我们先来看一下代码部分。点击黄色框中的split,可以代码和布局一起显示。
我们看到页面中已经有一个TextView。让我们先把 android:text ="Hello World!" 修改为 "你好,世界!" 试试看效果。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="你好,世界"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
之后我们发现屏幕中的文字也随着我们的修改变成了 "你好,世界!" 。 我的理解就是 android: 后面 的就是这个标签的属性,类似 html 中的 style="",也就是css。
接下来我来对TextView中基本常用的一些属性与css中的做一下对比,这样可以让我们理解起来更加容易。
| xlm | css | 描述 | 类型 |
|---|---|---|---|
| text | 直接写在标签中 | 标签中的文本 | 具体文本 |
| layout_width | width | 宽度 | wrap_content / match_parent(fill_parent) / 具体数值 |
| layout_height | height | 高度 | 同上 |
| background | background-color | 背景颜色 | 具体色值 |
| textColor | color | 文本颜色 | 同上 |
| gravity | text-align | 对齐方向 | left/center/right |
| textSize | font-size | 字体大小 | 具体数值 |
| textStyle | font-style | 字体样式 | normal/bold/italic |
我们先试用一下这些属性,看看是什么效果。
<TextView
android:layout_width="20dp"
android:layout_height="60dp"
android:text="宽度"
android:textColor="#EA5246" />
<TextView
android:layout_width="match_parent"
android:layout_height="10dp"
android:text="高度"
android:textColor="#EA5246" />
<TextView
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="背景颜色"
android:background="#000000"
android:textColor="#EA5246" />
<TextView
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="字体颜色"
android:textColor="#EA5246" />
<TextView
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="对齐方向"
android:gravity="center" />
<TextView
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="字体大小"
android:textSize="30dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="字体样式"
android:textStyle="bold|italic" />
我们今天先了解一下,TextView 属性的使用方法。现在看来TextView中的属性与CSS中的属性值与用法大体上相似,还有其他属性就在具体使用到的时候我们在逐步学习。