Do what you want to do

プログラミングとかとか

RadioButton, RadioGroup を使ってみる

今回はラジオボタンを使ってみます。

開発環境

レイアウト

まずはレイアウト。 ラジオボタンを2つ縦に並べてみました。 RadioButtonRadioGroupの中にいれてやることで 2つのラジオボタンを排他的(どちらか一方のみ選択可能)にできます。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.MainActivity">
    <RadioGroup
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/radioGroup" android:layout_marginTop="8dp"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="8dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp">
        <RadioButton
                android:text="@string/radiobutton1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/radioButton1"
                app:layout_constraintEnd_toEndOf="@+id/radioGroup"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toTopOf="@+id/radioGroup"
                app:layout_constraintStart_toStartOf="@+id/radioGroup"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:onClick="onRadioButtonClicked"/>
        <RadioButton
                android:text="@string/radiobutton2"
                android:layout_height="wrap_content"
                android:id="@+id/radioButton2"
                android:layout_width="match_parent"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="8dp"
                android:onClick="onRadioButtonClicked"/>
    </RadioGroup>
</android.support.constraint.ConstraintLayout>

onClickイベントを実装する

レイアウトのxmlandroid:onClick="onRadioButtonClicked"の記述がありますが、ここでActivity側のクリックイベントハンドラーと紐づけています。 Activity側のメソッドがこちらです。

fun onRadioButtonClicked(view: View) {
    if (view is RadioButton) {
        val checked = view.isChecked

        when (view.id) {
            R.id.radioButton1 ->
                if (checked) {
                }
            R.id.radioButton2 ->
                if (checked) {
                }
        }
    }
}

viewのidからどちらのラジオボタンのイベントかどうかを判定しています。

実行結果

radiobutton

参考

CheckBoxを使ってみる

今回はチェックボックスを使ってみます。

開発環境

レイアウト

まずはレイアウト。 チェックボックスを2つ縦に並べてみました。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.MainActivity">

    <CheckBox
            android:text="@string/checkbox_receive_email"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/checkBox1" android:layout_marginTop="16dp" app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="16dp"
            android:onClick="onCheckboxClicked"
            android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent"/>
    <CheckBox
            android:text="@string/checkbox_notification"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/checkBox2" app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="16dp" android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/checkBox1"
            android:onClick="onCheckboxClicked"
            android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent"/>
</android.support.constraint.ConstraintLayout>

onClickイベントを実装する

レイアウトのxmlandroid:onClick="onCheckboxClicked"の記述がありますが、ここでActivity側のクリックイベントハンドラーと紐づけています。 Activity側のメソッドがこちらです。

fun onCheckboxClicked(view: View) {
    if (view is CheckBox) {
        val checked: Boolean = view.isChecked

        when (view.id) {
            R.id.checkBox1 -> {
                if (checked) {
                    // do something
                } else {
                    // do something
                }
            }
            R.id.checkBox2 -> {
                if (checked) {
                    // do something
                } else {
                    // do something
                }
            }
        }
    }
}

上記は1つのメソッドを2つのチェックボックスで共有しているため、viewのidからどちらのチェックボックスのイベントかどうかを判定しています。 複雑になりそうならチェックボックス毎にメソッドを分けたほうがいいかもしれませんね。

実行結果

checkbox

参考

Toastを使ってメッセージを表示する

開発環境

Toastとは

画面の下にちょっとの間表示されるアレです。iOSにはないコンポーネントです。 そういえば最近Toast使ってるアプリ見かけなくなってきた?気のせい?まぁいいか。 今回はToastの表示方法です。とはいっても内容は軽め。

Toastの表示方法

import android.widget.Toast

fun didTapButton(view: View) {
    val message = "Sending message..."
    Toast
        .makeText(applicationContext, message, Toast.LENGTH_LONG)
        .show()
}

これだけ?え?これだけ。本当にこれだけです。 引数に以下を指定します。

  • applicationのContext
  • メッセージ
  • 表示長さ
    • LENGTH_SHORT(短め)もしくは LENGTH_LONG(長め)

実行結果

Toast.LENGTH_SHORT

f:id:katoj:20190328193127g:plain

Toast.LENGTH_LONG

f:id:katoj:20190328193202g:plain

おわりに

簡単に表示できました。 表示位置のカスタマイズ等もできるみたいですが、今日はこの辺で。

[Kotlin] LogクラスのTAGとしてActivityのクラス名を指定する処理をKotlinの拡張関数を使って共通化する

「毎回Activity毎にLogのTAG用変数作るとか面倒すぎじゃない?」

Kotlinなら拡張関数で簡単に共通化できそう... ということでやってみました。

LogクラスのTAGとしてActivityのクラス名を指定したい

「LogクラスのTAGとしてActivityのクラス名を出力する」ということはよくあるやり方だと思います。 JavaでもKotlinでも以前からAndroidではLog クラスを使ってログを出力できます。

Log クラス に載っているTAGの定義(Javaですが)を見てみましょう。

private static final String TAG = "MyActivity";

「いやいや、うーん、文字列入れてるだけじゃん。ってか毎回Activity毎にこれ定義するの?まじ?」

Kotlinの拡張関数を使って共通化

以下のようにKotlinを拡張してログを出力する関数を定義しました。 this::class.java.simpleName を使ってクラス名を取得しています。

import android.app.Activity
import android.util.Log

fun Activity.logd(message: String) {
    Log.d(this::class.java.simpleName, message)
}

使い方

使い方は簡単。Activityから定義したlogd 関数を呼ぶだけです。

fun didTapButton(view: View) {
    logd("user tapped the button.")
}

おわりに

クラス名を取得する処理を1箇所にまとめたことでActivity毎に毎回LogのTAG用変数を定義する必要がなくなりました。 Kotlinの拡張関数便利ですね。

Wearに簡単な通知を送ってみる

前回はWearのプロジェクトを作成したので今回は簡単な通知をWearに送ってみたいと思います。

mobileモジュールのMainActivityに適当にボタンを貼り付けて、ボタンのonClickで下記メソッドを呼んでみます。

    /**
     * Wearに通知します。
     */
    private void notifyToWear() {
        NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender()
                .setHintShowBackgroundOnly(true);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("通知タイトル")
                .setContentText("通知の内容をつらつらと")
                .setVibrate(new long[] {0, 300}) // 遅延0秒で300ミリ秒間振動する
                .extend(wearableExtender);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(0, notificationBuilder.build());
    }


結果はこのようにちゃんと通知が来ました。
※もちろんmobileの方にもちゃんと通知が来ます。

f:id:katoj:20150615234555p:plain


タイトルやテキストに加え、Vibrationも実装してみました。
通知自体はこのように簡単に送れますね!

背景画像やアイコンなどもろもろカスタマイズできそうです。

今回は以上です。

Android StudioでWearアプリのプロジェクトを作ってみる

LG Watch Urbaneを手に入れたこともそうですが最近Wearアプリに興味があります。
最近のAndroid開発はAndroid Studioを使用するのが一般的なようですのでAndroid StudioでWearアプリのプロジェクトを作ってみました。
ウィザードに従ってボタンをポチポチするだけですが画面キャプチャ残しておきたいと思います。


1. まずは Android Studioを起動して「Start a new Android Studio project 」をクリック。
f:id:katoj:20150614193522p:plain

2. 次にApplication nameとCompany Domain、Project locationを入力してNextをクリック。
※今回、アプリ名はHelloWear、Company DomainとProject locationはデフォルトのままとしました。
f:id:katoj:20150614193635p:plain

3. Target Android Devicesで「Phone and Tablet」と 「Wear」を選択してNextをクリック。
※Minimum SDKAPI 21としました。
f:id:katoj:20150614194001p:plain

4. Add an activity to Mobileでモバイル用のActivityを選択してNextをクリック。
※今回はBlank Activityにしました。
f:id:katoj:20150614194409p:plain

5. Customize the ActivityはそのままNextをクリック。
f:id:katoj:20150614194523p:plain

6. Add an activity to WearでWear用のActivity選択してNextをクリック。
※今回はBlank Wear Activityにしました。
f:id:katoj:20150614194536p:plain

7. Customize the ActivityはそのままでFinishをクリックするとプロジェクトが作成されます。
f:id:katoj:20150614194546p:plain

8. 作成されたプロジェクトを見るとmobileとは別にちゃんとWearのプロジェクトができているのがわかります。
f:id:katoj:20150614194556p:plain

今回は以上です。