Google Andriod Study Jam 學習筆記(1)

4 minute read

學習範圍

單元 1 ~ 單元 2 課程 2

Kotlin 語法

  1. 函式

    1
    2
    3
    
    fun <function name> : <return type> {
    
    }
    
  2. 輸出

    1
    2
    
    println("Hi") // 有換行
    print("Hi") // 沒換行
    
  3. 宣告變數

    1
    2
    
    val <variable name> = <variable value>
    val <variable name> = <class name>(parameter)
    
  4. 迴圈

    1
    2
    3
    
    repeat (<times>) {
    
    }
    
  5. class

    1
    2
    3
    4
    5
    6
    
    class <class name> (val <variable name>: <variable type>, ...) {
        val <variable name> = <variable type>
        fun <function name> {
    
        }
    }
    
    • inherit

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      
      // abstract: 未完整實作,無法執行個體化
      abstract class Dwelling(private var residents: Int) {
          abstract val buildingMaterial: String
          abstract val capacity: Int
      
          abstract fun floorArea(): Double
      
          fun hasRoom(): Boolean {
              return residents < capacity
          }
      
          fun getRoom() {
              if (capacity > residents) {
                  residents++
                  println("You got a room!")
              } else {
                  println("Sorry, at capacity and no rooms left.")
              }
          }
      
      }
      
      
      class SquareCabin(
          residents: Int, val length: Double) : Dwelling(residents) {
          override val buildingMaterial = "Wood"
          override val capacity = 6
      
          override fun floorArea(): Double {
              return length * length
          }
      
      }
      
      // 只有 open 跟 abstract 可以被繼承
      open class RoundHut(
          val residents: Int, val radius: Double) : Dwelling(residents) {
      
          override val buildingMaterial = "Straw"
          override val capacity = 4
      
          override fun floorArea(): Double {
              return PI * radius * radius
          }
      
          fun calculateMaxCarpetSize(): Double {
              val diameter = 2 * radius
              return sqrt(diameter * diameter / 2)
          }
      
      }
      
      class RoundTower(
          residents: Int,
          radius: Double,
          val floors: Int = 2) : RoundHut(residents, radius) {
      
          override val buildingMaterial = "Stone"
      
          override val capacity = floors * 4
      
          override fun floorArea(): Double {
              return super.floorArea() * floors
          }
      }
      
  6. IntRange

    1
    
    val tmp = 1..6 // tmp 是一個 type IntRange 的 variable, 範圍是 [1, 6]
    
  7. when

    1
    2
    3
    
    when (<variable>) {
        <value> -> <execute content>
    }
    

    其中 <value>可以是給定 variable

  8. with

    1
    2
    3
    
    with (instanceName) {
        // all operations to do with instanceName
    }
    

    搭配class的例子

    1
    2
    3
    4
    5
    6
    
    with(squareCabin) {
        println("\nSquare Cabin\n============")
        println("Capacity: ${capacity}")
        println("Material: ${buildingMaterial}")
        println("Has room? ${hasRoom()}")
    }
    

Android Studio

  1. UI

  2. hardcode
    不要 hardcode,把 text 的名稱弄到 string.xml
    ex.

    1
    2
    3
    4
    
    <resources>
        <string name="app_name">Happy Birthday</string>
        <string name="happy_birthday_text">Happy Birthday, Sam!</string>
    </resources>
    

    text 那格就變成填 @string/happy_birthday_text

  3. object reference (其實我不知道應該把它歸在寫 app 還是語法)

    1
    2
    3
    
    val rollButton: Button = findViewById(R.id.button)
    val resultTextView: TextView = findViewById(R.id.textView)
    resultTextView.text = "6"
    

    findViewById會在 layout 中找到 Button,然後把Button的 object reference 存到 rollButton 裡

  4. 顯示訊息給使用者

    1
    2
    
    val toast = Toast.makeText(this, "Dice Rolled!", Toast.LENGTH_SHORT)
    toast.show()
    
  5. 設定貨幣(數字)規格

    1
    
    val formattedTip = NumberFormat.getCurrencyInstance().format(tip)
    
  6. binding

    activitity_main.xml 中

    1
    
    binding.tipResult.text = getString(R.string.tip_amount, formattedTip)
    

    string.xml 中

    1
    
    <string name="tip_amount">Tip Amount: %s</string>
    
  7. 打完字收起小鍵盤

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    
     private fun handleKeyEvent(view: View, keyCode: Int): Boolean {
         if (keyCode == KeyEvent.KEYCODE_ENTER) {
             // Hide the keyboard
             val inputMethodManager =
                 getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
             inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
             return true
         }
         return false
     }
    
  8. 螢幕轉向、不同尺寸

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
     <ScrollView
         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_height="match_parent"
         android:layout_width="match_parent">
    
         <androidx.constraintlayout.widget.ConstraintLayout
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:padding="16dp"
             tools:context=".MainActivity">
    
             ...
         </ConstraintLayout>
    
     </ScrollView>
    
  9. unittest

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
    @RunWith(AndroidJUnit4::class)
    class CalculatorTests {
    
        @get:Rule()
        val activity = ActivityScenarioRule(MainActivity::class.java)
    
        @Test
        fun calculate_20_percent_tip() {
            onView(withId(R.id.cost_of_service_edit_text))
                .perform(typeText("50.00"))
    
            onView(withId(R.id.calculate_button)).perform(click())
    
            onView(withId(R.id.tip_result))
                .check(matches(withText(containsString("$10.00"))))
        }
    }