Open15

【Kotlin】Android Kotlin Fundamentalsをやってみた:Lesson2

カワグチミサキカワグチミサキ

Lesson2:Layouts

Lesson2-1:LinearLayout using the Layout Editor

About Meプロジェクトを作成。名前を表示させる
strings.xml
<resources>
    <string name="app_name">AboutMe</string>
    <string name="name">misaki</string>
</resources>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/name_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/name"
        android:textSize="@dimen/text_size"
        android:textAlignment="center"/>
</LinearLayout>
fontSizeをOption+Enterし、dimens.xmlにサイズを登録する
dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="text_size">20sp</dimen>
</resources>
marginとpaddingもdimensに登録する。

activity_main.xmlのDesignを開き、右のボタンをクリックしてPick a Resourseを開く。

Dimension ValueをクリックしNew Dimension Valueを開き、登録したい値を入力する

登録後は下記のようになる

dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="text_size">20sp</dimen>
    <dimen name="small_padding">8sp</dimen>
    <dimen name="layout_margin">16dp</dimen>
</resources>
スタイル抽出する

Component Tree→Refactor→Extract Styleで抽出したいスタイルを選択する。

styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="NameStyle">
        <item name="android:layout_marginTop">@dimen/layout_margin</item>
        <item name="android:fontFamily">@font/roboto</item>
        <item name="android:paddingTop">@dimen/small_padding</item>
        <item name="android:textColor">@color/black</item>
        <item name="android:textSize">@dimen/text_size</item>
    </style>
</resources>
カワグチミサキカワグチミサキ

画像を配置する

ImageVIewをドラッグ&ドロップし、画像を選択する。

contentDescriptionを設定する。

strings.xml
<resources>
    <string name="yellow_star" />
</resources>
activity_main.xml
<ImageView
        android:id="@+id/star_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/layout_margin"
        android:contentDescription="@string/yellow_star"
        app:srcCompat="@android:drawable/btn_star_big_on"/>
カワグチミサキカワグチミサキ

ScrollViewを追加する

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:layout_marginTop="@dimen/layout_margin"
    android:orientation="vertical"
    android:paddingTop="@dimen/small_padding"
    android:paddingStart="@dimen/layout_padding"
    android:paddingEnd="@dimen/layout_padding"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/name_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/name"
        android:textAlignment="center"
        style="@style/NameStyle" />

    <EditText
        android:id="@+id/nickname_edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <ImageView
        android:id="@+id/star_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/layout_margin"
        android:contentDescription="@string/yellow_star"
        app:srcCompat="@android:drawable/btn_star_big_on"/>

    <ScrollView
        android:id="@+id/bio_scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/bio_text"
            style="@style/NameStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:lineSpacingMultiplier="1.2"
            android:text="@string/bio" />
    </ScrollView>
</LinearLayout>
strings.xml
<resources>
    <string name="app_name">AboutMe</string>
    <string name="name">misaki</string>
    <string name="yellow_star" />
    <string name="bio">Hi, my name is Aleks.
\n\nI love fish.
\n\nThe kind that is alive and swims around in an aquarium or river, or a lake, and definitely the ocean.
\nFun fact is that I have several aquariums and also a river.
\n\nI like eating fish, too. Raw fish. Grilled fish. Smoked fish. Poached fish - not so much.
\nAnd sometimes I even go fishing.
\nAnd even less sometimes, I actually catch something.
\n\nOnce, when I was camping in Canada, and very hungry, I even caught a large salmon with my hands.
\n\nI\'ll be happy to teach you how to make your own aquarium.
\nYou should ask someone else about fishing, though.\n\n</string>
</resources>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="text_size">20sp</dimen>
    <dimen name="small_padding">8sp</dimen>
    <dimen name="layout_margin">16dp</dimen>
    <dimen name="layout_padding">16sp</dimen>
</resources>

カワグチミサキカワグチミサキ

Lesson2-2:Add user interactivity

EditText を追加

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:layout_marginTop="@dimen/layout_margin"
    android:orientation="vertical"
    android:paddingTop="@dimen/small_padding"
    android:paddingStart="@dimen/layout_padding"
    android:paddingEnd="@dimen/layout_padding"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/name_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/name"
        android:textAlignment="center"
        style="@style/NameStyle" />

    <EditText
        android:id="@+id/nickname_edit"
        style="@style/NameStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/what_is_your_nickname"
        android:inputType="textPersonName"
        android:textAlignment="center"/>

    <ImageView
        android:id="@+id/star_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/layout_margin"
        android:contentDescription="@string/yellow_star"
        app:srcCompat="@android:drawable/btn_star_big_on"/>

    <ScrollView
        android:id="@+id/bio_scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/bio_text"
            style="@style/NameStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:lineSpacingMultiplier="1.2"
            android:text="@string/bio" />
    </ScrollView>
</LinearLayout>
カワグチミサキカワグチミサキ

DONEボタンを追加する

colors.xmlの中身が変わっていて、ボタンの色はapp:backgroundTintで指定すると変更できた。

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:layout_marginTop="@dimen/layout_margin"
    android:orientation="vertical"
    android:paddingTop="@dimen/small_padding"
    android:paddingStart="@dimen/layout_padding"
    android:paddingEnd="@dimen/layout_padding"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/name_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/name"
        android:textAlignment="center"
        style="@style/NameStyle" />

    <EditText
        android:id="@+id/nickname_edit"
        style="@style/NameStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/what_is_your_nickname"
        android:inputType="textPersonName"
        android:textAlignment="center"/>

    <Button
        android:id="@+id/done_button"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="@dimen/layout_margin"
        android:fontFamily="@font/roboto"
        app:backgroundTint="@color/colorAccent"
        android:text="@string/done" />

    <ImageView
        android:id="@+id/star_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/layout_margin"
        android:contentDescription="@string/yellow_star"
        app:srcCompat="@android:drawable/btn_star_big_on"/>

    <ScrollView
        android:id="@+id/bio_scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/bio_text"
            style="@style/NameStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:lineSpacingMultiplier="1.2"
            android:text="@string/bio" />
    </ScrollView>
</LinearLayout>
カワグチミサキカワグチミサキ

DONEボタンを押すとニックネームを表示できるようにする


  • visibilityについて
    • visible:ビュー表示。
    • Invisible:ビュー非表示。レイアウト内のスペースを占有。
    • gone:ビュー非表示。レイアウト内のスペースを占有しない。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:layout_marginTop="@dimen/layout_margin"
    android:orientation="vertical"
    android:paddingTop="@dimen/small_padding"
    android:paddingStart="@dimen/layout_padding"
    android:paddingEnd="@dimen/layout_padding"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/name_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/name"
        android:textAlignment="center"
        style="@style/NameStyle" />

    <EditText
        android:id="@+id/nickname_edit"
        style="@style/NameStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/what_is_your_nickname"
        android:inputType="textPersonName"
        android:textAlignment="center"/>

    <Button
        android:id="@+id/done_button"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="@dimen/layout_margin"
        android:fontFamily="@font/roboto"
        app:backgroundTint="@color/colorAccent"
        android:text="@string/done"
        android:onClick="addNickname"/>

    <TextView
        android:id="@+id/nickname_text"
        style="@style/NameStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAlignment="center"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/star_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/layout_margin"
        android:contentDescription="@string/yellow_star"
        app:srcCompat="@android:drawable/btn_star_big_on"/>

    <ScrollView
        android:id="@+id/bio_scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/bio_text"
            style="@style/NameStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:lineSpacingMultiplier="1.2"
            android:text="@string/bio" />
    </ScrollView>
</LinearLayout>
MainActivity.kt
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    findViewById<Button>(R.id.done_button).setOnClickListener{
      addNickname(it)
    }
  }

  private fun addNickname(view: View) {
    val editText = findViewById<EditText>(R.id.nickname_edit)
    val nicknameTextView = findViewById<TextView>(R.id.nickname_text)

    nicknameTextView.text = editText.text
    editText.visibility = View.GONE
    // DONEボタンを非表示
    view.visibility = View.GONE
    nicknameTextView.visibility = View.VISIBLE

    // キーボードを非表示にする
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0)
  }
}
カワグチミサキカワグチミサキ

ニックネームを更新できるようにする

TextViewをタップした時にEditTextとButtonが表示されるようにする。



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

    findViewById<TextView>(R.id.nickname_text).setOnClickListener {
      updateNickname(it)
    }
  }

  private fun updateNickname(view: View) {
    val editText = findViewById<EditText>(R.id.nickname_edit)
    val doneButton = findViewById<Button>(R.id.done_button)

    editText.visibility = View.VISIBLE
    doneButton.visibility = View.VISIBLE
    view.visibility = View.GONE

    editText.requestFocus()

    // キーボードを表示する
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(editText, 0)
  }
}
カワグチミサキカワグチミサキ

TextViewにpaddingと背景色を追加する

activity_main.xml
<TextView
        android:id="@+id/nickname_text"
        style="@style/NameStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAlignment="center"
        android:visibility="gone"
        android:background="@color/colorAccent"
        android:paddingBottom="@dimen/small_padding"/>
カワグチミサキカワグチミサキ

Lesson2-3:ConstraintLayout using the Layout Editor

ColorMyViewsプロジェクトを作成

TextViewを表示する

activity_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/box_one_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:fontFamily="@font/roboto"
        android:text="@string/box_one"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="margin_wide">16dp</dimen>
    <dimen name="box_text_size">24sp</dimen>
</resources>
styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="whiteBox">
        <item name="android:fontFamily">@font/roboto</item>
        <item name="android:textSize">@dimen/box_text_size</item>
        <item name="android:background">@android:color/holo_green_light</item>
        <item name="android:textAlignment">center</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@android:color/white</item>
    </style>
</resources>
strings.xml
<resources>
    <string name="app_name">ColorMyViews</string>
    <string name="box_one">Box One</string>
</resources>
カワグチミサキカワグチミサキ

TextViewを追加

activiey_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/box_one_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:fontFamily="@font/roboto"
        android:text="@string/box_one"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/box_two_text"
        style="@style/whiteBox"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:text="@string/box_two"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/box_one_text" />

</androidx.constraintlayout.widget.ConstraintLayout>
strings.xml
<resources>
    <string name="app_name">ColorMyViews</string>
    <string name="box_one">Box One</string>
    <string name="box_two">Box Two</string>
</resources>
カワグチミサキカワグチミサキ

TextView ビューのチェーンを作成する

TextViewを選択し、Chains→Create Vertical Chainを選択

上下の制約を追加する


左右の制約を追加



余白を追加する
activity_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/box_one_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:fontFamily="@font/roboto"
        android:text="@string/box_one"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/box_two_text"
        style="@style/whiteBox"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:text="@string/box_two"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/box_one_text" />

    <TextView
        android:id="@+id/box_three_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:text="@string/box_three"
        app:layout_constraintBottom_toTopOf="@+id/box_four_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/box_two_text"
        app:layout_constraintTop_toTopOf="@+id/box_two_text" />

    <TextView
        android:id="@+id/box_four_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:layout_marginBottom="@dimen/margin_wide"
        android:text="@string/box_four"
        app:layout_constraintBottom_toTopOf="@+id/box_five_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/box_two_text"
        app:layout_constraintTop_toBottomOf="@+id/box_three_text" />

    <TextView
        android:id="@+id/box_five_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:text="@string/box_five"
        app:layout_constraintBottom_toBottomOf="@+id/box_two_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/box_two_text"
        app:layout_constraintTop_toBottomOf="@+id/box_four_text" />

</androidx.constraintlayout.widget.ConstraintLayout>
カワグチミサキカワグチミサキ

タップすると背景色が変わるようにする

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

    setListeners()
  }

  private fun setListeners() {
    val boxOneText = findViewById<TextView>(R.id.box_one_text)
    val boxTwoText = findViewById<TextView>(R.id.box_two_text)
    val boxThreeText = findViewById<TextView>(R.id.box_three_text)
    val boxFourText = findViewById<TextView>(R.id.box_four_text)
    val boxFiveText = findViewById<TextView>(R.id.box_five_text)

    val rootConstraintLayout = findViewById<View>(R.id.constraint_layout)

    val clickableViews: List<View> =
      listOf(
        boxOneText, boxTwoText, boxThreeText,
        boxFourText, boxFiveText, rootConstraintLayout,
      )
    for (item in clickableViews) {
      item.setOnClickListener { makeColored(it) }
    }

  }

  private fun makeColored(view: View) {
    when (view.id) {
      R.id.box_one_text -> view.setBackgroundColor(Color.DKGRAY)
      R.id.box_two_text -> view.setBackgroundColor(Color.GRAY)

      R.id.box_three_text -> view.setBackgroundColor(Color.BLUE)
      R.id.box_four_text -> view.setBackgroundColor(Color.MAGENTA)
      R.id.box_five_text -> view.setBackgroundColor(Color.BLUE)

      else -> view.setBackgroundColor(Color.LTGRAY)
    }

  }
}
カワグチミサキカワグチミサキ

テキストを追加する

activity_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:id="@+id/constraint_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/box_one_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:fontFamily="@font/roboto"
        android:text="@string/box_one"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/box_two_text"
        style="@style/whiteBox"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:text="@string/box_two"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/box_one_text" />

    <TextView
        android:id="@+id/box_three_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:text="@string/box_three"
        app:layout_constraintBottom_toTopOf="@+id/box_four_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/box_two_text"
        app:layout_constraintTop_toTopOf="@+id/box_two_text" />

    <TextView
        android:id="@+id/box_four_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:layout_marginBottom="@dimen/margin_wide"
        android:text="@string/box_four"
        app:layout_constraintBottom_toTopOf="@+id/box_five_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/box_two_text"
        app:layout_constraintTop_toBottomOf="@+id/box_three_text" />

    <TextView
        android:id="@+id/box_five_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:text="@string/box_five"
        app:layout_constraintBottom_toBottomOf="@+id/box_two_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/box_two_text"
        app:layout_constraintTop_toBottomOf="@+id/box_four_text" />

    <TextView
        android:id="@+id/label_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:fontFamily="@font/roboto"
        android:text="@string/how_to_play"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBaseline_toBaselineOf="@+id/info_text"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/info_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:layout_marginBottom="@dimen/margin_wide"
        android:fontFamily="@font/roboto"
        android:text="@string/tap_the_boxes_and_buttons"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/label_text"
        app:layout_constraintTop_toBottomOf="@+id/box_two_text"
        app:layout_constraintVertical_bias="0.0"/>

</androidx.constraintlayout.widget.ConstraintLayout>
strings.xml
<resources>
    <string name="how_to_play">How to play:</string>
    <string name="tap_the_boxes_and_buttons">Tap the screen and buttons.</string>
</resources>
カワグチミサキカワグチミサキ

ボタンを追加する

activity_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:id="@+id/constraint_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/box_one_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:fontFamily="@font/roboto"
        android:text="@string/box_one"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/box_two_text"
        style="@style/whiteBox"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:text="@string/box_two"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/box_one_text" />

    <TextView
        android:id="@+id/box_three_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:text="@string/box_three"
        app:layout_constraintBottom_toTopOf="@+id/box_four_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/box_two_text"
        app:layout_constraintTop_toTopOf="@+id/box_two_text" />

    <TextView
        android:id="@+id/box_four_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:layout_marginBottom="@dimen/margin_wide"
        android:text="@string/box_four"
        app:layout_constraintBottom_toTopOf="@+id/box_five_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/box_two_text"
        app:layout_constraintTop_toBottomOf="@+id/box_three_text" />

    <TextView
        android:id="@+id/box_five_text"
        style="@style/whiteBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:text="@string/box_five"
        app:layout_constraintBottom_toBottomOf="@+id/box_two_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/box_two_text"
        app:layout_constraintTop_toBottomOf="@+id/box_four_text" />

    <TextView
        android:id="@+id/label_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:fontFamily="@font/roboto"
        android:text="@string/how_to_play"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBaseline_toBaselineOf="@+id/info_text"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/info_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginEnd="@dimen/margin_wide"
        android:layout_marginBottom="@dimen/margin_wide"
        android:fontFamily="@font/roboto"
        android:text="@string/tap_the_boxes_and_buttons"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/label_text"
        app:layout_constraintTop_toBottomOf="@+id/box_two_text"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/red_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:text="@string/button_red"
        android:visibility="visible"
        app:layout_constraintBaseline_toBaselineOf="@+id/yellow_button"
        app:layout_constraintEnd_toStartOf="@+id/yellow_button"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"/>

    <Button
        android:id="@+id/yellow_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_wide"
        android:layout_marginTop="@dimen/margin_wide"
        android:layout_marginBottom="@dimen/margin_wide"
        android:text="@string/button_yellow"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/green_button"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/red_button"
        app:layout_constraintTop_toBottomOf="@+id/info_text"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/green_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:text="@string/button_green"
        app:layout_constraintBaseline_toBaselineOf="@+id/yellow_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/yellow_button" />

</androidx.constraintlayout.widget.ConstraintLayout>
strings.xml
<resources>
    <string name="button_red">RED</string>
    <string name="button_yellow">YELLOW</string>
    <string name="button_green">GREEN</string>
</resources>
MainActivity.kt
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    setListeners()
  }

  private fun setListeners() {

    val boxOneText = findViewById<TextView>(R.id.box_one_text)
    val boxTwoText = findViewById<TextView>(R.id.box_two_text)
    val boxThreeText = findViewById<TextView>(R.id.box_three_text)
    val boxFourText = findViewById<TextView>(R.id.box_four_text)
    val boxFiveText = findViewById<TextView>(R.id.box_five_text)

    val rootConstraintLayout = findViewById<View>(R.id.constraint_layout)

    val redButton = findViewById<Button>(R.id.red_button)
    val greenButton = findViewById<Button>(R.id.green_button)
    val yellowButton = findViewById<Button>(R.id.yellow_button)

    val clickableViews: List<View> =
      listOf(
        boxOneText, boxTwoText, boxThreeText,
        boxFourText, boxFiveText, rootConstraintLayout,
        redButton, greenButton, yellowButton
      )

    for (item in clickableViews) {
      item.setOnClickListener { makeColored(it) }
    }
  }

  private fun makeColored(view: View) {
    val boxThreeText = findViewById<TextView>(R.id.box_three_text)
    val boxFourText = findViewById<TextView>(R.id.box_four_text)
    val boxFiveText = findViewById<TextView>(R.id.box_five_text)

    when (view.id) {
      R.id.box_one_text -> view.setBackgroundColor(Color.DKGRAY)
      R.id.box_two_text -> view.setBackgroundColor(Color.GRAY)

      R.id.box_three_text -> view.setBackgroundColor(Color.BLUE)
      R.id.box_four_text -> view.setBackgroundColor(Color.MAGENTA)
      R.id.box_five_text -> view.setBackgroundColor(Color.BLUE)

      R.id.red_button -> boxThreeText.setBackgroundResource(R.color.my_red)
      R.id.yellow_button -> boxFourText.setBackgroundResource(R.color.my_yellow)
      R.id.green_button -> boxFiveText.setBackgroundResource(R.color.my_green)

      else -> view.setBackgroundColor(Color.LTGRAY)
    }
  }
}
カワグチミサキカワグチミサキ

Lesson2-4:Data binding basics

findViewById() を多用するとアプリが重くなるのでデータバインディングを使用するのが望ましい

bindingを有効にする

build.gradle (Module
buildFeatures {
    dataBinding true
}

layoutタグで囲う

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingStart="@dimen/padding"
        android:paddingEnd="@dimen/padding">

        <TextView
            android:id="@+id/name_text"
            style="@style/NameStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@={myName.name}"
            android:textAlignment="center" />

        <TextView
            android:id="@+id/nickname_text"
            style="@style/NameStyle"
            android:text="@={myName.nickname}"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:visibility="gone" />

        <EditText
            android:id="@+id/nickname_edit"
            style="@style/NameStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/what_is_your_nickname"
            android:inputType="textPersonName"
            android:textAlignment="center" />

        <Button
            android:id="@+id/done_button"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="@dimen/layout_margin"
            android:fontFamily="@font/roboto"
            android:text="@string/done"
            android:textAlignment="center" />

        <ImageView
            android:id="@+id/star_image"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/layout_margin"
            android:contentDescription="@string/yellow_star"
            app:srcCompat="@android:drawable/btn_star_big_on" />

        <ScrollView
            android:id="@+id/bio_scroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="@dimen/layout_margin">

            <TextView
                android:id="@+id/bio_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:lineSpacingMultiplier="@dimen/line_spacing_multiplier"
                android:text="@string/bio"
                android:textAppearance="@style/NameStyle" />

        </ScrollView>
    </LinearLayout>
</layout>

MainActivityでbindingオブジェクトを作成する

bindingオブジェクトの変数を作成する

MainActivity.kt
class MainActivity : AppCompatActivity() {
  private lateinit var binding: ActivityMainBinding
}

setContentView()関数を書き換える

MainActivity.kt
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    }
}

findViewByIdを書き換える

MainActivity.kt
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        binding.doneButton.setOnClickListener {
            addNickname(it)
        }

    }

    private fun addNickname(view: View) {
        binding. apply {
            nicknameEdit.visibility = View.GONE
            doneButton.visibility = View.GONE
            nicknameText.visibility = View.VISIBLE
        }

        // Hide the keyboard.
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
}

MyName データ クラスを作成

MyName.kt
package com.example.android.aboutme

data class MyName(var name: String = "", var nickname: String = "")
レイアウトにデータを追加する

テキストをandroid:text="@={myName.name}"に変更する

activity_main.kt
<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="myName"
            type="com.example.android.aboutme.MyName" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingStart="@dimen/padding"
        android:paddingEnd="@dimen/padding">

        <TextView
            android:id="@+id/name_text"
            style="@style/NameStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@={myName.name}"
            android:textAlignment="center" />

        <TextView
            android:id="@+id/nickname_text"
            style="@style/NameStyle"
            android:text="@={myName.nickname}"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:visibility="gone" />

        <EditText
            android:id="@+id/nickname_edit"
            style="@style/NameStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/what_is_your_nickname"
            android:inputType="textPersonName"
            android:textAlignment="center" />

        <Button
            android:id="@+id/done_button"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="@dimen/layout_margin"
            android:fontFamily="@font/roboto"
            android:text="@string/done"
            android:textAlignment="center" />

        <ImageView
            android:id="@+id/star_image"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/layout_margin"
            android:contentDescription="@string/yellow_star"
            app:srcCompat="@android:drawable/btn_star_big_on" />

        <ScrollView
            android:id="@+id/bio_scroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="@dimen/layout_margin">

            <TextView
                android:id="@+id/bio_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:lineSpacingMultiplier="@dimen/line_spacing_multiplier"
                android:text="@string/bio"
                android:textAppearance="@style/NameStyle" />

        </ScrollView>
    </LinearLayout>
</layout>
データを作成する
MainActivity.kt
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    private val myName: MyName = MyName("Aleks Haecky")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        binding.myName = myName

        binding.doneButton.setOnClickListener {
            addNickname(it)
        }

    }

    private fun addNickname(view: View) {
        binding. apply {
            myName?.nickname = nicknameEdit.text.toString()
            // 更新されたバインディング オブジェクトの値で UI が更新されるようにする
            invalidateAll()
            nicknameEdit.visibility = View.GONE
            doneButton.visibility = View.GONE
            nicknameText.visibility = View.VISIBLE
        }

        // Hide the keyboard.
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
}