この記事は2020年07月23日に投稿しました。
目次
リンク
1. はじめに
こんにちは、iOSのエディタアプリPWEditorの開発者の二俣です。
今回は業務で使用しているAndroidでRadioButtonを使用する方法についてです。
2. AndroidでRadioButtonを使用する
AndroidでRadioButtonを使用するには、以下のような実装になります。
ポイントは1つのグループとしたいRadioButtonはRadioGroup内に配置することです。
またチェックされた時に呼び出されるリスナーは、RadioGroupに設定します。
実装例
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" android:orientation="vertical"> <!-- ラジオボタンをグループ化するためRadioGroupを配置します --> <RadioGroup android:id="@+id/fruitsRadioGroup" android:layout_width="match_parent" android:layout_height="match_parent" > <RadioButton android:id="@+id/appleRadioButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="リンゴ" /> <RadioButton android:id="@+id/bananaRadioButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="バナナ" /> <RadioButton android:id="@+id/orangeRadioButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="ミカン" /> </RadioGroup> </LinearLayout>
MainActivity.kt
package info.paveway.sampleradiobutton import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.RadioButton import android.widget.RadioGroup import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // ラジオボタングループにリスナーを設定します。 val listener = FruitsRadioGroupOnCheckedChangeListener() val radioGroup = findViewById<RadioGroup>(R.id.fruitsRadioGroup) radioGroup.setOnCheckedChangeListener(listener) // リンゴのラジオボタンをチェック状態にします。 val appleRadioButton = findViewById<RadioButton>(R.id.appleRadioButton) appleRadioButton.isChecked = true } // ラジオボタンがチェックされた時に呼び出されるリスナークラス private inner class FruitsRadioGroupOnCheckedChangeListener : RadioGroup.OnCheckedChangeListener { override fun onCheckedChanged(radioGroup: RadioGroup?, checkedRadioButtonId: Int) { // チェックされたラジオボタンを取得します。 val radioButton = findViewById<RadioButton>(checkedRadioButtonId) // チェックされたラジオボタンの表示タイトルをトースト表示します。 Toast.makeText(applicationContext, radioButton.text, Toast.LENGTH_SHORT).show() } } }
実行結果
API Reference
RadioButtonクラス
RadioGroupクラス
3. おわりに
RadioButtonは他の言語同様の使い方なので、そんなに難しくないと思います。
リンク
紹介している一部の記事のコードはGitlabで公開しています。
興味のある方は覗いてみてください。
私が勤務しているニューラルでは、主に組み込み系ソフトの開発を行っております。
弊社製品のハイブリッドOS [Bi-OS][Bi-OS]は高い技術力を評価されており、特に制御系や通信系を得意としています。
私自身はiOSモバイルアプリやウィンドウズアプリを得意としております。
ソフトウェア開発に関して相談などございましたら、お気軽にご連絡ください。
また一緒に働きたい技術者の方も随時募集中です。
興味がありましたらご連絡ください。
EMAIL : info-nr@newral.co.jp / m-futamata@newral.co.jp
TEL : 042-523-3663
FAX : 042-540-1688