安卓零基础入门开发简易教程(Kotlin)

一、介绍安卓界面activity

1、创建第一个安卓程序

安装安卓开发环境

已安装完毕AndroidStudio,安装指导可以参考: 《安卓开发入门之开发环境搭建

创建第一个安卓工程

1. 新建工程

image

image

2. 最后一步,点击“Finish”,工程效果图如下。

image

3. 选择设备,点击绿色箭头运行。

image

4. App运行效果图:

image

附录:创建安卓模拟器

  1. 点击如下图标


    image

    image
  2. 选择硬件类型
    image
  3. 选择系统镜像
    如果对应的镜像还未下载,旁边会出现Download按钮,需要先点击下载镜像.


    image
  4. 配置设备相关信息


    image
  5. 完成后,界面如下:


    image
  6. 关闭上面的界面,回到运行程序的主界面,就可以选择到新增的模拟器了


    image

2.安卓基本界面:activity

  • app运行效果图


    image
  • activity代码
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
  • 界面布局xml文件
<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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="程序园中猿"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • manifest文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.cxyzy.demo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3.安卓界面跳转

3.1不带数据跳转

  • app运行效果图


    image
  • 代码
  1. 第一个界面Activity
class FirstActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_first)
        textView.setOnClickListener {
            startActivity(Intent(this, SecondActivity::class.java))
        }
    }
}
  1. 第一个界面布局xml文件
<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=".FirstActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击查看第二页"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3.第二个界面Activity

class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
    }
}
  1. 第二个界面布局xml文件
<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=".FirstActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="程序园中猿_第二页."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3.2带数据跳转

  • app运行效果图


    image
  • 代码
  1. 第一个界面Activity
class FirstActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_first)
        textView.setOnClickListener {
            val intent = Intent(this, SecondActivity::class.java)
            //传递字符串类型
            intent.putExtra("name", "程序园中猿")
            //传递整型
            intent.putExtra("age", 99)
            //传递布尔
            intent.putExtra("isOK", true)
            startActivity(intent)
        }
    }
}
  1. 第一个界面布局xml文件
<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=".FirstActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击查看第二页"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3.第二个界面Activity

class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
        //获取字符串值
        val name = intent.getStringExtra("name")
        //获取整型值
        val age = intent.getIntExtra("age", 0)
        //获取布尔值
        val isOk = intent.getBooleanExtra("isOk", true)
        showContent(name, age, isOk)
    }

    private fun showContent(name: String?, age: Int, isOk: Boolean) {
        descTextView.text = "名字:$name;年龄:$age;isOk:$isOk"
    }
}
  1. 第二个界面布局xml文件
<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=".FirstActivity">

    <TextView
        android:id="@+id/descTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="程序园中猿_第二页."
        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

  1. 简介
    显示文本
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="程序园中猿" />
  • activity代码
//设置文本
textView.text = "程序园中猿"
//设置文本颜色
textView.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary))

文本输入控件:EditText

普通文本输入

  1. 简介
    用于输入普通文本
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Click me to confess" />
  • activity代码
//设置输入框内容
editText.setText("程序园中猿")

密码输入

  1. 简介
    用于输入密码
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<EditText
    android:id="@+id/pwdEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword" />
  • activity代码
//设置密码输入框内容
pwdEditText.setText("123456")

按钮控件

普通按钮:Button

  1. 简介
    显示按钮
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAllCaps="false"
    android:text="Touch me" />
  • activity代码
//设置按钮文字
button.text = "Touch me"
//设置点击事件
button.setOnClickListener {
    Toast.makeText(this, "Feels good", Toast.LENGTH_SHORT).show()
}

图片按钮:ImageButton

  1. 简介
    显示带有图片的按钮
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<ImageButton
    android:id="@+id/imageButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@android:drawable/ic_input_add" />
  • activity代码
//设置按钮图片
imageButton.setImageResource(R.mipmap.ic_launcher)
//设置点击事件
imageButton.setOnClickListener {
    Toast.makeText(this, "Go on", Toast.LENGTH_SHORT).show()
}

单选框:RadioButton

  1. 简介
    实现单选功能
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<RadioButton
    android:id="@+id/radioButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="单选框" />
  • activity代码

单选框组:RadioGroup

  1. 简介

  2. 效果图


    image
  3. 使用方法

  • xml布局文件代码
<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="单选框1" />

    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="单选框2" />
</RadioGroup>
  • activity代码
//获取选中的单选框
val selectedRadioButton = findViewById<RadioButton>(radioGroup.checkedRadioButtonId)
selectedRadioButton?.let {
    //获取选中单选框的文字
    val text = selectedRadioButton.text
}

复选框:CheckBox

  1. 简介
    实现多选功能
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="复选框" />
  • activity代码
//设置复选框显示文字
checkBox.text = "复选框"
//获取是否被选中
val isChecked = checkBox.isChecked

开关:Switch

  1. 简介
    显示开关
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<Switch
    android:id="@+id/switch1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="开关" />

  • activity代码
//设置开关显示文字
switch1.text="开关"
//获取是否被选中
val isChecked = switch1.isChecked

状态开关按钮:ToggleButton

  1. 简介
    具有按下和恢复状态的按钮
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<ToggleButton
    android:id="@+id/toggleButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAllCaps="false"
    android:textOff="已关"
    android:textOn="已开" />
  • activity代码
//获取是否被选中
val isChecked = toggleButton.isChecked

图片显示控件:ImageView

  1. 简介
    显示图片
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@mipmap/ic_launcher" />
  • activity代码
//修改图片
imageView.setImageResource(R.mipmap.ic_launcher)

进度条

进度条:ProgressBar

  1. 简介
    执行耗时操作时,给用户等待提示.
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  • activity代码
//隐藏进度条
progressBar.visibility = View.GONE
//显示进度条
progressBar.visibility = View.VISIBLE

横向进度条:ProgressBar

  1. 简介
    用于显示进度

显示确定耗时的进度条

  1. 效果图


    image
  2. 使用方法
  • xml布局文件代码
<ProgressBar
    android:id="@+id/horizontalProgressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:progress="30" />
  • activity代码
//设置进度
horizontalProgressBar.progress = 50

显示不确定耗时的进度条

  1. 效果图


    显示不确定耗时的进度
  2. 使用方法
  • xml布局文件代码
<ProgressBar
    android:id="@+id/horizontalProgressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:indeterminate="true" />
  • activity代码
//隐藏进度条
horizontalProgressBar.visibility = View.GONE
//显示进度条
horizontalProgressBar.visibility = View.VISIBLE

可拖动进度条:SeekBar

  1. 简介
    通过拖动可以控制进度,如用于控制播放进度、音量大小等

连续可拖动进度条

  1. 效果图


    image
  2. 使用方法
  • xml布局文件代码
<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:progress="50" />
  • activity代码
//设置进度
seekBar.progress = 60

分段可拖动进度条

  1. 效果图


    image
  2. 使用方法
  • xml布局文件代码
<SeekBar
    android:id="@+id/discreteSeekBar"
    style="@style/Widget.AppCompat.SeekBar.Discrete"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="10"
    android:progress="3" />
  • activity代码
//设置进度
discreteSeekBar.progress = 5

评分控件:RatingBar

  1. 简介
    用于评分
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<RatingBar
    android:id="@+id/ratingBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numStars="5"
    android:rating="2" />
  • activity代码
//设置评分
ratingBar.rating = 3.0f

搜索框

  1. 简介
    用于搜索
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<SearchView
    android:id="@+id/searchView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
  • activity代码
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
    // 当点击搜索按钮时触发该方法
    override fun onQueryTextSubmit(query: String?): Boolean {
        Toast.makeText(mContext, query, Toast.LENGTH_SHORT).show()
        return false
    }

    // 当搜索内容改变时触发该方法
    override fun onQueryTextChange(newText: String?): Boolean {
        Toast.makeText(mContext, newText, Toast.LENGTH_SHORT).show()
        return false
    }
})

日历和时间控件

日历控件:CalendarView

  1. 简介
    用于选择日期
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<CalendarView
    android:id="@+id/calendarView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
    </LinearLayout>
  • activity代码
//设置初始日期
val date = SimpleDateFormat("yyyy/MM/dd").parse("2020/02/02")
date?.let { calendarView.date = it.time }

//获取用户选择的日期
calendarView.setOnDateChangeListener { calendarView, year, month, dayOfMonth ->
    Toast.makeText(mContext, "日期:${year}年${month + 1}月${dayOfMonth}日", Toast.LENGTH_SHORT)
        .show()
}

日历控件:DatePicker

  1. 简介
    用于选择日期,
  2. 效果图


    image
  3. 使用方法
  • xml布局文件代码
<DatePicker
    android:id="@+id/datePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  • activity代码
//设置初始日期,设置监听获取用户选择的日期
datePicker.init(2020, 2, 2) { datePicker, year, month, dayOfMonth ->
    Toast.makeText(mContext, "日期:${year}年${month + 1}月${dayOfMonth}日", Toast.LENGTH_SHORT)
        .show()
}

时间控件

  1. 简介
    用于选择时间

  2. 效果图

  3. 使用方法

  • xml布局文件代码

  • activity代码

列表


待续

列表

网络访问

三、Fragment

四、广播

五、数据存储

SharedPreferences

SQLite数据库

文件

简易读写样例

  1. Manifest文件添加权限声明
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  1. 添加申请权限开源包依赖
implementation 'com.afollestad:assent:2.3.1'
  1. 申请权限及读写文件代码
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        writeFileBtn.setOnClickListener {
            checkPermissionAndWriteFile()
        }
        readFileBtn.setOnClickListener {
            checkPermissionAndReadFile()
        }
    }

    /**
     * 检查权限并写文件
     */
    private fun checkPermissionAndWriteFile() {
        runWithPermissions(Permission.WRITE_EXTERNAL_STORAGE) {
            writeFile("test data")
        }
    }

    /**
     * 写文件
     */
    private fun writeFile(data: String) {
        val testFile = getTestFile()
        getTestFile().writeText(data)
        Toast.makeText(this, "filePath:${testFile.absolutePath}", Toast.LENGTH_SHORT).show()
    }

    /**
     * 检查权限并写文件
     */
    private fun checkPermissionAndReadFile() {
        runWithPermissions(Permission.WRITE_EXTERNAL_STORAGE) {
            readFile()
        }
    }

    /**
     * 读文件
     */
    private fun readFile() {
        val testFile = getTestFile()
        val content = testFile.readText()
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show()
    }

    private fun getTestFile(): File {
        val dir = File(getExternalFilesDir(null)?.absolutePath, "tmp")
        dir.mkdirs()

        return File(dir.absolutePath + "/test.txt")
    }
}
  1. 完整源代码
    https://gitee.com/cxyzy1/androidStart/tree/master/FileDemo

六、运行时权限

读取sd卡

录音

摄像头

位置

访问通讯录

七、常用工具

toast

八、实例

天气预报app

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容

  • 一、简历准备 1、个人技能 (1)自定义控件、UI设计、常用动画特效 自定义控件 ①为什么要自定义控件? Andr...
    lucas777阅读 5,200评论 2 54
  • 1. 基本介绍 Node的Buffer介绍Buffer 类用于在 TCP 流或文件系统操作等场景中处理字节流。Bu...
    红笔黑字阅读 683评论 0 1
  • 前几天给闺蜜小西(唐明)聊天(此处给自己脸上贴金一块---她是格尔木作协主席),她问我还写文章吗,我说早就不...
    prettyhuhu阅读 307评论 0 0
  • 1】学习❥Y ️1. 学习David老师视频 2.事业课学习 3. BEC 4.学习一些精油护肤相关的知识,为后面...
    Dianne1阅读 181评论 0 0