Android入门 | 控件与布局

本文详述了Android开发中的常用控件如TextView、Button、EditText、ImageView、ProgressBar及AlertDialog的使用方法,并探讨了LinearLayout、RelativeLayout和FrameLayout三种基本布局的特性与应用。此外,还介绍了自定义控件的创建,包括如何引入布局和注册点击事件。同时讲解了ListView与RecyclerView的使用,包括列表的定制、性能优化和点击事件处理,最后提到了Kotlin的延迟初始化和密封类的概念。
摘要由CSDN通过智能技术生成

1.常用控件的使用方法

Android 给我们提供了大量的 UI 控件,合理地使用这些控件可以非常轻松的编写出相当不错的界面,下面我们就挑选集中常用的控件,详细介绍一下它们的使用方法。

1.1 TextView

TextView 用于再界面上显示一段文本信息,接下来我们看看 TextView 的更多用法。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is TextView" />

</LinearLayout>


除此之外我们还可以为宽和高设置固定大小,单位是dp,这是一种与屏幕密度无关的尺寸单位,可以保证在不同分辨率的手机上显示的效果尽可能的一致。

由于 TextView 默认都是居左上角对齐的,但是由于文字的内容不够长,所以从效果上看不出来,我们可以添加如下代码设置 TextView 的对齐方式。

android:gravity="center"

gravity 一共有 topbottomstartendcenter 等可选属性,并且可以使用 |进行分割从而设置多个属性,其中 center 的效果等同于 center_vertical|center_horizontal,表示文字在垂直和水平方向上都居中对齐。

除此之外我们还可以对 TextView 的字体颜色和大小进行设置,

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="This is TextView"
    android:textSize="24sp"
    android:textColor="#0f0" />

textSize 属性用于设置文字大小,它的单位是 sp,这样当用户修改了系统中文字的大小时该文字也会发生变化。 textColor 用于设置文字的颜色。

当然 TextView 还有很多其它的属性,在这里就不一一介绍了。

1.2 Button

Button 是程序用于和用户进行交互的一个重要控件,它可配置的属性和 TextView 差不多。

在 xml 中加入 Button

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button" />

在 xml 中加入 Button 后的界面效果


在 Android 系统中会默认将按钮上的英文字母全部转换为大写,如果不想要这样可以为按钮添加android:textAllCaps="false" 属性进行设置。

除此之外,我们还可以为按钮添加监听器

  • 利用 Java 单抽象方法接口特性

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            button.setOnClickListener({
                // 在此处添加逻辑
            })
        }
    }
    
  • 使用实现接口的方式注册监听器

    class MainActivity : AppCompatActivity(), View.OnClickListener {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            button.setOnClickListener(this)
        }
    
        override fun onClick(v: View?) {
            when (v?.id) {
                R.id.button -> {
                    // 在此处添加逻辑
                }
            }
        }
    }
    

1.3 EditText

EditText 是程序用于和用户进行交互的另一个重要控件,它允许用户在控件里输入和编辑内容,并可以在程序中对这些内容进行处理。EditText 的应用场景应该算是非常普遍了,发短信、发微博、聊QQ等等,在进行这些操作时,你不得不使用到 EditText

在 xml 中加入 EditText

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

除此之外 Android 系统内置了一个十分常用的功能,就是当用户未输入时在输入框中有一行提示文字,当用户输入后提示文字就没了,要想实现这个功能只需要在控件中加入android:hint="XXX",其中 XXX 就是提示的文本,下面我们来尝试一下。

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Type something here" />

不过随着输入内容的不断增多,EditText 会被不断拉长,这是由于 EditText 的高度是 wrap_content。因此它总能包含住里面的内容,但是当输入内容过多时,界面就会变得非常难看,在此我们可以使用 android:maxLines 属性来解决这个问题。

修改 xml 文件

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLines="2"
    android:hint="Type something here" />

这样设置之后无论如何都只会在 EditText 中显示两行文字

使用 EditText + Button 获取输入的内容

class MainActivity : AppCompatActivity(), View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener(this)

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.button -> {
                // 获取 editText 中的文本内容并转换为字符串
                val str = editText.text.toString()
                // 将获取到的内容使用 Toast 显示出来
                Toast.makeText(this, str, Toast.LENGTH_SHORT).show()
            }
        }
    }
}

1.4 ImageView

ImageView 是用于在界面上展示图片的一个控件,它可以让我们的程序界面变得更加丰富多彩。

图片通常是放在以 drawable 开头的目录下的,并且要带上具体的分辨率。现在最主流的手机屏幕分辨率大多是 xxhdpi 的,所以我们在 res 目录下创建一个 drawable-xxhdpi 目录,然后将图片放到该目录下。

修改 xml 文件

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/img_1" />

引入图片通过 android:src 属性。

点击按钮实现图片的切换。

override fun onClick(v: View?) {
    when (v?.id) {
        R.id.button -> {
            // 点击按钮实现图片的切换
            imageView.setImageResource(R.drawable.img_2)
        }
    }
}

1.5 ProgressBar

ProgressBar 用于在界面上显示一个进度条,表示我们的程序正在加载一些数据。

使用 ProgressBar

<ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />


旋转的进度条可以表示系统正在加载数据,那么加载完之后就需要将进度条隐藏,那么可以通过 android:visibility 属性进行设置,该属性有三个值 分别是:visibleinvisiblegone。其中 visible 表示可见(默认值),invisible 表示不可见,但是它仍然占据着原来的位置和大小。 gone 表示不可见,而且不占据原来的位置和空间。

除了使用 xml 设置之外,也可以使用 setVisibility() 方法,传入 View.VISIBLEView.INVISIBLEView.GONE 这3种值。

实现点击按钮显示与隐藏进度条

override fun onClick(v: View?) {
    when (v?.id) {
        R.id.button -> {
            if (progressBar.visibility == View.VISIBLE) {
                progressBar.visibility = View.GONE
            } else {
                progressBar.visibility = View.VISIBLE
            }
        }
    }
}

另外,还可以为进度条设置不同的样式,刚刚是圆形的进度条,通过 style 属性可以将它改为水平的进度条

修改 xml 文件

<ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    style="?android:attr/progressBarStyleHorizontal"
    android:max="100"
    />

通过以上代码将进度条设置为水平之后还将进度条的最大进度设置为了100.

通过点击按钮增加进度条的进度。

override fun onClick(v: View?) {
    when (v?.id) {
        R.id.button -> {
            progressBar.progress = progressBar.progress + 10;
        }
    }
}

1.6 AlertDialog

AlertDialog 可以在当前界面弹出一个对话框,这个对话框时顶置于所有界面元素之上的,能够屏蔽其他控件的交互能力,因此 AlertDialog 一般用于提示一些重要的内容或者警告等信息。比如为了防止用户误删重要内容,在删除前弹出一个确认对话框。

override fun onClick(v: View?) {
    when (v?.id) {
        R.id.button -> {
            AlertDialog.Builder(this).apply {
                setTitle("This is Dialog")
                setMessage("Something important")
                setCancelable(false)
                setPositiveButton("OK") {
                    dialog, which ->
                }
                setNegativeButton("Cancel") {
                    dialog, which ->
                }
                show()
            }
        }
    }
}

这里首先通过 AlertDialog.Builder 构建了一个对话框,然后通过 Kotlin 中的 apply() 函数,在 apply() 函数中为这个对话框设置了标题、内容、是否使用 Back 键取消以及对话框中的确认和取消按钮,最后调用 show() 方法进行显示。

2.详解 3 种基本布局

一个丰富的界面是由很多个控件组成的,那么我们如何才能让各个控件都有条不紊的摆放在界面上,而不是乱糟糟的呢?这就需要借助布局来实现了,布局是一种可用于放置很多控件的容器,它可以按照一定的规律调整内部控件的位置,从而编写出精美的界面,除了在布局中放置控件外,还可以在布局内嵌套布局。

它们的关系如下图所示:

2.1 LinearLayout

LinearLayout 又称作线性布局,是一种非常常用的布局。正如它的名字所描述的一样,这个布局会将它所包含的控件在线性的方向上依次排列。

2.1.1 为线性布局指定方向

  • 纵向排列 vertical
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1" />
    
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 2" />
    
        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 3" />
    </LinearLayout>
    

  • 横向排列 horizontal
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值