«

android studio 笔记

时间:2022-11-13 15:25     作者:独元殇     分类: 其他


因为安卓在手上拿着,方便一点,看看能不能学一丢丢小技术,做点生活小工具。

不深入学。

android studio 的环境配置很麻烦,稀奇古怪的错误很多,不再整。

Start

简单一个

以下是一个很简单的安卓程序。具体架构我也不懂,反正这个就相当于 main.cpp 这种。

MainActivity.kt:

package com.example.testone

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.example.testone.ui.theme.TestoneTheme
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.padding

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) { // 此应用的入口
        super.onCreate(savedInstanceState)
        setContent {  // 通过可组合函数,定义布局
            TestoneTheme {
                // A surface container using the 'background' color from the theme
                Surface(  // 界面的某一部分。这是一个容器
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Greeting("Android")
                }
            }
        }
    }
}

@Composable  // 标这玩意的,可被其他函数调用,告诉编译器,xxx 可被生成 UI。这种函数无法返回任何内容
fun Greeting(name: String) {
    Surface(color = Color.Magenta) {
        Text(text = "Hi! my name is  $name!", modifier = Modifier.padding(24.dp))
    }
}

@Preview(showBackground = true)  // 展示 background 。预览函数
@Composable
fun DefaultPreview() {  // 很酷的功能,无序重构整个应用,便可看到效果
    TestoneTheme {
        Greeting("likehong")
    }
}

Kotlin

神奇的 when

代码如下

fun main() {
    val trafficLightColor = "Yellow"

    when (trafficLightColor) {
        "Red" -> println("Stop")
        "Yellow" -> println("Slow")
        "Green" -> println("Go")
        else -> println("Invalid traffic-light color")
    }
}

// or

fun main() {
    val x = 3

    when (x) {
        2 -> println("x is a prime number between 1 and 10.")
        3 -> println("x is a prime number between 1 and 10.")
        5 -> println("x is a prime number between 1 and 10.")
        7 -> println("x is a prime number between 1 and 10.")
        else -> println("x isn't a prime number between 1 and 10.")
    }
}

in 的一个关于质数的案例

fun main() {
    val x = 3

    when (x) {
        2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
        in 1..10 -> println("x is a number between 1 and 10, but not a prime number.")
        else -> println("x isn't a prime number between 1 and 10.")
    }
}

any 这个语法的案例

fun main() {
    val x: Any = 20

    when (x) {
        2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
        in 1..10 -> println("x is a number between 1 and 10, but not a prime number.")
        is Int -> println("x is an integer number, but not between 1 and 10.")
        else -> println("x isn't an integer number.")
    }
}

不过我现在对语法不感兴趣,明天或有时间了再学。

布局

  1. 线性布局

  2. 相对布局

  3. 帧布局

android studio 简单初始化步骤

  1. 新建项目,选择空白模板 Empty Activity。

  2. 起项目名,弄清楚“保存路径”。

  3. 编程语言选择 kotlin, SDK 选择合适的。

  4. 等待片刻,下方倘若没有红色错误,代表 相关文件 下载成功

  5. 进入主活动布局文件 “Activity——main.xml”

  6. 右方显示模块的左上角 小眼睛 图标,选 Show System UI

  7. (通常第一个活动称为 main activity,必须在 class mainactivity 提供版面配置的详细资料)

  8. 左边的文件导航上面的下拉框选择 android,这样下面有 app -- res ...

  9. (layout -- activity_main.xml 就是主活动布局文件)

  10. 在布局中,我们可拖动一个按钮到布局

  11. 设置垂直和水平条件来定位

  12. 底部出现 warning,还有一个 fix 按钮。点击 fix 按钮以修正。

  13. 之后在弹出框中,Resource value 中输入 “ROLL” 或其他想显示的字符串,回车。

修改 hello world 字体大小等等

  1. 在右上角的搜索框中搜索 textsize ,更改后面的值

  2. 向下滚动,下面的 common attributes 的 text 里可修改文字。(当然,现在把里面的字符删除掉)

  3. 下面的带 工具 图标的 text 选项,是为开发人员设计的测试字符,比如输入 1 (执行时不会显示这个 1)。

  4. 然后编码

(其他注意事项....  运行后,如果修改代码,那么就要把模拟器上面一个什么 apply code   change 点击了。)

小案例 掷色子

// activaty_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="34sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="@string/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>


// MainActivity.kt


package com.example.side_learn1

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)  // 主布局文件

        /* 上面的 R 可理解为 res 中的 r,资源活动包 */

        /* 找到 UI 文件 */
        /* 下面这行 前面的 Button 指按钮的类型,后面的是 id 名
            R.< type >.< id >
        */
        val rollButton: Button = findViewById(R.id.button2)
        rollButton.setOnClickListener {
            rollDice()
        }

    }

    private fun rollDice() {
        /* 掷色子 */
        val dice = Dice(6)
        val diceRoll = dice.roll()
        val resultTextView: TextView = findViewById(R.id.textView)
        resultTextView.text = diceRoll.toString()
    }
}

class Dice(val numSides: Int) {
    fun roll(): Int {
        return (1..6).random()
    }
}

小案例 获取设备当前电量

(什么 UI 什么什么同上,只写那个 MainActivity.kt)

package com.example.a20230601

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val rollButton: Button = findViewById(R.id.button2)  // 获取按钮
        rollButton.setOnClickListener {  // 点击按钮后的事件就写在这里面
            clickJapan()
        }
    }

    private fun clickJapan() {  // 点击按钮后的事件(点击"Japan"按钮)
        val resultTextView: TextView = findViewById(R.id.textView)
         resultTextView.text = getBatteryLevel(this)  // = 后的东西,会被显示
    }

}

/* -------------------[ 下面写程序吧 ]----------------------------- */

/* 获取系统电量信息 */
fun getBatteryLevel(context: Context): String {
    val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
    val batteryStatus: Intent? = context.registerReceiver(null, intentFilter)
    val level: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
    val scale: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
    val batteryPct: Float = level / scale.toFloat()
    return "当前电量是:${(batteryPct * 100).toInt()}%"
}

img

标签: 原创 文档 android

推荐阅读: