安卓开发教程03:TextView基本属性与CSS属性

332 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

今天我们来看Android 中最最基本的一个UI控件,TextView(文本框)由于我之前是做前端的,所以我看到这个组件的时候 第一反应这不就是给 < p > 嘛。接下来看见TextView 的属性,一股熟悉的味道扑面而来。心想那这块上手应该很快了,那么让来我们来看一下具体的使用方法。

TextView 基本属性

首先让我们来先写一个 TextView。 还是回到我们上次创建的mytest 项目中来,找到app -> src -> main -> res -> layout 目录下,我们可以看到有一个activity_main.xml的文件。双击打开,我们一般会看到一个这样的页面。

QQ截图20220930084236.jpg

是不是一股熟悉的味道,像不像网页三剑客中的Dreamweaver。我们先来看一下代码部分。点击黄色框中的split,可以代码和布局一起显示。

image.png

我们看到页面中已经有一个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中的做一下对比,这样可以让我们理解起来更加容易。

xlmcss描述类型
text直接写在标签中标签中的文本具体文本
layout_widthwidth宽度wrap_content / match_parent(fill_parent) / 具体数值
layout_heightheight高度同上
backgroundbackground-color背景颜色具体色值
textColorcolor文本颜色同上
gravitytext-align对齐方向left/center/right
textSizefont-size字体大小具体数值
textStylefont-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" />

QQ截图20220930093443.jpg

我们今天先了解一下,TextView 属性的使用方法。现在看来TextView中的属性与CSS中的属性值与用法大体上相似,还有其他属性就在具体使用到的时候我们在逐步学习。