一。创建项目
项目名Beer Adviser
二。更新布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:gravity="center"
android:orientation="vertical">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/beer_color"
android:layout_gravity="center"
android:layout_margin="16dp"
android:entries="@array/beer_colors"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/find_beer"
style="?android:attr/buttonBarButtonStyle"
android:id="@+id/find_beer"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"
android:id="@+id/brands"
tools:text="@string/brands"/>
</LinearLayout>
三。增加资源strings.xml
<resources>
<string name="app_name">Beer Adviser</string>
<string name="find_beer">Find Beer</string>
<string name="brands">No beer selected</string>
<string-array name="beer_colors">
<item>Light</item>
<item>Amber</item>
<item>Brown</item>
<item>Dark</item>
</string-array>
</resources>
四。响应点击
MainActivity.kt
文章来源:https://www.toymoban.com/news/detail-657059.html
package com.demo.beeradviser
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Spinner
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val findBeer = findViewById<Button>(R.id.find_beer)
findBeer.setOnClickListener {
val beerColor = findViewById<Spinner>(R.id.beer_color)
val color = beerColor.selectedItem
val beerList = getBeers(color.toString())
val beers = beerList.reduce { str, item -> str + '\n' + item }
val brands = findViewById<TextView>(R.id.brands)
brands.text = beers
}
}
fun getBeers(color: String): List<String> {
return when (color) {
"Light" -> listOf("Jail Pale Ale", "Lager Lite")
"Amber" -> listOf("Jack Amber", "Red Moose")
"Brown" -> listOf("Brown Bear Beer", "Bock Brownie")
else -> listOf("Gout Stout", "Dark Daniel")
}
}
}
知识点:文章来源地址https://www.toymoban.com/news/detail-657059.html
到了这里,关于Android2:构建交互式应用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!