LoginSignup
6
3

More than 3 years have passed since last update.

【超初心者向け】Android入門 Button編

Posted at

はじめに

前回Android入門 TextView編をやったので今回はButtonに関して解説していきたいと思います。

記事の対象

  • Androidアプリ開発初心者
  • Androidをこよなく愛す人
  • 前回の記事を読んだ方

Buttonとは

その名の通りボタンです。
押して何かしらのアクションを起こすものですね。

1. activity_main.xmlにButtonを追加する。

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/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="Click!"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

Buttonの中に書いてあることは最初は無視でいいです。
簡単に説明すると、Buttonがどのくらいの大きさで(layout:width, layout_height)、上にどれだけ余白をつけて(layout_marginTop)、ボタンのテキストはどうするか(text)、 どの位置に配置するか(layout_constraintHogetHoge)です。

興味がある方は色々試してみてくださいねー!

2. MainActivity.ktでButtonを定義する

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

        val textView = findViewById<TextView>(R.id.textView)

        textView.text = "こんにちは、世界"

        val button = findViewById<Button>(R.id.button)
    }
}

前回の続きからなので、textViewが定義されたままですね。

その下にボタンでボタンを定義していきましょう

勘がいい方はお気づきかと思いますが、findViewByIdメソッドがxml上で定義したidを元にViewを見つけてくれるんですね!

3.クリックリスナーを定義する

クリックリスナーというのはボタンをクリックした時にどんな動作をさせるかというものです。
今回はボタンをクリックしたらtextViewの文字がClicked!になるようにしましょう。

先ほどのval button = ~~の下に以下の一文を加えてください


button.setOnClickListener {
    textView.text = "Clicked!"
}

4.実行

さぁ実行してみましょう!
どうでしょう?

ボタンをクリックしたらこんにちは、世界がClicked!になりましたね。

5.まとめ

今回はButtonの解説をしていきました。

上記の通りにやっても動かない等あれば気軽にコメントやTwitterのDMに質問ください!

6
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3