質問編集履歴
1
ソースコードを追記しました
test
CHANGED
File without changes
|
test
CHANGED
@@ -15,3 +15,141 @@
|
|
15
15
|
|
16
16
|
|
17
17
|
私はKotlin初心者なので何がなにやらサッパリ分からなくて困っております。どなたか助言をお願い致します。
|
18
|
+
|
19
|
+
|
20
|
+
|
21
|
+
```Kotlin
|
22
|
+
|
23
|
+
package com.example.stopwatch
|
24
|
+
|
25
|
+
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
import android.support.v7.app.AppCompatActivity
|
30
|
+
|
31
|
+
import android.os.Bundle
|
32
|
+
|
33
|
+
import android.os.Handler
|
34
|
+
|
35
|
+
|
36
|
+
|
37
|
+
|
38
|
+
|
39
|
+
class MainActivity : AppCompatActivity() {
|
40
|
+
|
41
|
+
|
42
|
+
|
43
|
+
val handler = Handler()
|
44
|
+
|
45
|
+
var timeValue = 0
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
override fun onCreate(savedInstanceState: Bundle?) {
|
50
|
+
|
51
|
+
super.onCreate(savedInstanceState)
|
52
|
+
|
53
|
+
setContentView(R.layout.activity_main)
|
54
|
+
|
55
|
+
// View要素を変数に代入(配置したビュー要素にアクセス)
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
val timeText = findViewById(R.id.timeText) as TextView
|
60
|
+
|
61
|
+
val startButton = findViewById(R.id.start) as Button
|
62
|
+
|
63
|
+
val stopButton = findViewById(R.id.stop) as Button
|
64
|
+
|
65
|
+
val resetButton = findViewById(R.id.reset) as Button
|
66
|
+
|
67
|
+
|
68
|
+
|
69
|
+
val runnable = object : Runnable {
|
70
|
+
|
71
|
+
override fun run() {
|
72
|
+
|
73
|
+
timeValue++
|
74
|
+
|
75
|
+
|
76
|
+
|
77
|
+
timeToText(timeValue)?.let {
|
78
|
+
|
79
|
+
timeText.text = it
|
80
|
+
|
81
|
+
}
|
82
|
+
|
83
|
+
handler.postDelayed(this, 1000)
|
84
|
+
|
85
|
+
}
|
86
|
+
|
87
|
+
}
|
88
|
+
|
89
|
+
|
90
|
+
|
91
|
+
startButton.setOnClickListener {
|
92
|
+
|
93
|
+
handler.post(runnable)
|
94
|
+
|
95
|
+
}
|
96
|
+
|
97
|
+
|
98
|
+
|
99
|
+
stopButton.setOnClickListener {
|
100
|
+
|
101
|
+
handler.removeCallbacks(runnable)
|
102
|
+
|
103
|
+
}
|
104
|
+
|
105
|
+
|
106
|
+
|
107
|
+
resetButton.setOnClickListener {
|
108
|
+
|
109
|
+
handler.removeCallbacks(runnable)
|
110
|
+
|
111
|
+
timeValue = 0
|
112
|
+
|
113
|
+
timeToText()?.let {
|
114
|
+
|
115
|
+
timeText.text = it
|
116
|
+
|
117
|
+
}
|
118
|
+
|
119
|
+
}
|
120
|
+
|
121
|
+
}
|
122
|
+
|
123
|
+
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
private fun timeToText(time: Int = 0): String? {
|
128
|
+
|
129
|
+
return if (time < 0) {
|
130
|
+
|
131
|
+
null
|
132
|
+
|
133
|
+
} else if (time == 0) {
|
134
|
+
|
135
|
+
"00:00:00"
|
136
|
+
|
137
|
+
} else {
|
138
|
+
|
139
|
+
val h = time / 3600
|
140
|
+
|
141
|
+
val m = time % 3600 / 60
|
142
|
+
|
143
|
+
val s = time % 60
|
144
|
+
|
145
|
+
"%1$02d:%2$02d:%3$02d".format(h, m, s)
|
146
|
+
|
147
|
+
}
|
148
|
+
|
149
|
+
}
|
150
|
+
|
151
|
+
}
|
152
|
+
|
153
|
+
|
154
|
+
|
155
|
+
```
|