XMLレイアウト + Retrofit通信
activity_main.xml
<TextView
android:id="@+id/counterText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="カウント: 0"
android:textSize="20sp"
android:layout_marginTop="16dp" />
<Button
android:id="@+id/incrementButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="カウントアップ" />
MainActivity
package com.example.myapplication
import com.example.myapplication.ChatApi
import com.example.myapplication.ChatRequest
import com.example.myapplication.ChatResponse
import com.example.myapplication.ApiClient
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
private var count = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val inputMessage = findViewById<EditText>(R.id.inputMessage)
val sendButton = findViewById<Button>(R.id.sendButton)
val resultText = findViewById<TextView>(R.id.resultText)
val counterText = findViewById<TextView>(R.id.counterText)
val incrementButton = findViewById<Button>(R.id.incrementButton)
sendButton.setOnClickListener {
val message = inputMessage.text.toString()
val request = ChatRequest(name = "田中", job = "エンジニア")
ApiClient.chatApi.sendMessage(request).enqueue(object : Callback<ChatResponse> {
override fun onResponse(call: Call<ChatResponse>, response: Response<ChatResponse>) {
if (response.isSuccessful) {
val body = response.body()
resultText.text = if (body != null) {
"name: ${body.name}\njob: ${body.job}\nid: ${body.id}\ncreatedAt: ${body.createdAt}"
} else {
"応答なし"
}
} else {
resultText.text = "エラーコード: ${response.code()}"
}
}
override fun onFailure(call: Call<ChatResponse>, t: Throwable) {
resultText.text = "通信失敗: ${t.localizedMessage}"
}
})
}
incrementButton.setOnClickListener {
count++
counterText.text = "カウント: $count"
}
}
}
特徴 XMLレイアウト + Retrofit通信 Jetpack Compose
UIの作り方 XMLファイルで定義 Kotlinコードで定義
表示の変更 TextView.setText()などで明示的に更新 状態が変われば自動で再描画される
直感性 複雑で古いUIも対応できるが手間 シンプルでモダンなUIが書きやすい
可読性・保守性 XMLとKotlinが分かれて見づらくなる すべてKotlinに書けるので読みやすい
プレビュー Android Studioでリアルタイムプレビュー可能 同じく可(Compose Preview)
モダンな描き方はjetpack composeが良さそう
Androidの次の学習項目
⭐️ 高 ViewModel + State管理 複雑なUI状態を安全に管理。画面回転にも強い。
⭐️ 高 Repositoryパターン RetrofitやRoomとの接続を分離して保守性UP
⭐️ 高 Room(ローカルDB) オフライン保存・データ永続化の基礎
⭐️ 高 データの非同期処理(Coroutines / Flow) 通信やDB操作を効率的に行う。非同期処理の本命
⭐️ 中 UIのアニメーション Composeのanimate*関数で滑らかなUI体験
⭐️ 中 Dependency Injection(Hilt) テストしやすい、保守しやすい設計にするための基盤
⭐️ 中 Jetpack Compose Navigation(複雑版) 引数付き遷移、戻る処理、BottomNavなどを扱う
⭐️ 低〜中 テスト(Unit, UIテスト) 安定したアプリを作るには重要。ただし最初は後回しでもOK
⭐️ 低 デザインパターン(MVVMなど) 設計力を高めたいときに学習
いまいちピンとこないものが多いですが、結構ありますね。