1.前言
界面是Android开发最先接触到的知识,也是日常工作中的基本任务,整理了一份关于Android界面开发中所需要用到的控件,温故而知新,不亦乐乎~
2.文字显示-TextView
文字显示是Android程序最基本的功能,用于文字显示的Android控件只有一个,那就是TextView。
TextView的基本属性如下所示,绝大部分的功能只需要设置这几个属性即可满足要求。
属性 | 说明 |
---|---|
text | 要显示的文本 |
textSize | 文字的大小值 |
textColor | 文本的颜色,格式为#RGB值 |
gravity | 文本的放置位置,常用center |
background | 控件的背景色 |
layout_gravity | 整个控件在外部容器的放置位置 |
<TextView
android:id="@+id/tv_name" //控件的ID名称,基本必备
android:text="Hello World!" //文本显示
android:gravity="center" //文本显示在控件的中间
android:textSize="25sp" //文字的大小为25sp
android:layout_gravity="center" //控件放置在外部容器的中间
android:textColor="@color/black" //文本的颜色为黑色
android:background="#8DA5BD" //控件的背景色为#8DA5BD
android:layout_width="100dp" //控件的宽度,必须有
android:layout_height="100dp"/> //控件的高度,必须有
3.文本输入-EditText
EditText用于输入文本,继承自TextView,可使用上述TextView全部属性,EditText常用的基本属性如下:
属性 | 说明 |
---|---|
hint | 文本输入提示,当有字符输入时自动隐藏 |
inputType | 输入的文本类型,常用textPassword密码输入文本;number只能输入数字 |
imeOptions | 键盘右下解回车键的类型,常用actionGo表示前往 |
singleLine | 是否为单行文本,imeOptions要生效必须要设置此属性为true |
maxLength | 最长可输入的长度 |
digits | 限制要输入的字符 |
<EditText
android:id="@+id/et_name"
android:layout_width="150dp"
android:layout_height="50dp"
android:hint="要输入的文本"
android:inputType="textPassword"
android:imeOptions="actionGo"
android:singleLine="true"
android:maxLength="50" //最大输入文本长度为50
android:digits="12345678a" //只能输入1到8和a这些字符
/>
4.图片显示-ImageView
Android上经常要显示一些图片,使UI更加美观。ImageView专门用于图片显示,使用background属性也可以显示图片,但没有ImageView那么灵活,提供了设置图片属性的多种方式。
属性 | 说明 |
---|---|
src | 要显示的图片资源 |
scaleType | 图片的缩放类型,常用centerCrop/center |
alpha | 图片的透明度,01,完全透明不透明 |
<ImageView
android:id="@+id/iv_icon"
android:src="@drawable/ic_start" //设置要显示的图片资源
android:scaleType="centerCrop" //表示图片居中裁剪填充满整个控件
android:layout_gravity="start|bottom" //表示左边与下边,用|可拼接两个属性
android:layout_width="100dp"
android:layout_height="100dp"
android:alpha="0.5" //设置图片度为50%
/>
5.点击按钮
按钮的作用是响应用户的操作,Android的按钮控件有两种Button与ImageButton,两者的区别在于ImageButton继承于ImageView,本质是一个图片控件;Button继承于TextView,本质是一个文本控件。
5.1 Button
基本属性与TextView一致,不再赘述,需要补充的是Button一般会设置不同状态的背景,会创建一个Selector,按下状态显示另外一个背景。
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed" />
<item android:state_focused="true"
android:drawable="@drawable/button_focused" />
<item android:drawable="@drawable/button_normal" />
</selector>
5.2 ImageButton
该控件与Button的功能一致,使用图片代替文字作为按钮的显示。
未完待续~