LoginSignup
8
7

More than 5 years have passed since last update.

Builder パターンで Toast の生成を行う

Last updated at Posted at 2015-02-18

はじめに

Toast 関連のコードを見栄えよく書きたいなということで、Builder パターンを使った Util クラスを作ってみました。AlertDailog のような感覚で使えます。

使い方

こんな感じで使えます。

new ToastUtil.Builder(getActivity())
        .text("メッセージ")
        .show();

new ToastUtil.Builder(getActivity())
        .resId(R.string.message_hogehoge)
        .duration(Toast.LENGTH_LONG)
        .gravity(ToastUtil.CENTER)
        .show();

メッセージは、テキスト指定でも id 指定でも OK です。
duration は任意指定ですが、Toast.LENGTH_SHORT をデフォルトで指定しているため、Toast.LENGTH_LONG にしたいときに指定します。
gravity も任意指定です。中央表示したいとき用に、ToastUtil.CENTER という定数を用意しています。

コード

こちらの記事を参考に作りました。
http://qiita.com/disc99/items/840cf9936687f97a482b

public class ToastUtil {

    public static final int CENTER = Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL;

    private Context context;
    private CharSequence text;
    private int length;
    private Integer gravity;

    public static class Builder {
        private Context context;
        private CharSequence text;
        private int duration;
        private Integer gravity;

        public Builder(Context context) {
            this.context = context;

            // Default Value
            this.text = "No messages";
            this.duration = Toast.LENGTH_SHORT;
        }

        public Builder text(CharSequence message) {
            this.text = message;
            return this;
        }

        public Builder resId(int resId) {
            this.text = context.getText(resId);
            return this;
        }

        public Builder duration(int duration) {
            this.duration = duration;
            return this;
        }

        public Builder gravity(int gravity) {
            this.gravity = gravity;
            return this;
        }

        public ToastUtil create() {
            return new ToastUtil(this);
        }

        public void show() {
            new ToastUtil(this).show();
        }
    }

    private ToastUtil(Builder builder) {
        this.context = builder.context;
        this.text = builder.text;
        this.length = builder.duration;
        this.gravity = builder.gravity;
    }

    public void show() {
        Toast toast = Toast.makeText(context, text, length);
        if (gravity != null) {
            toast.setGravity(gravity, 0, 0);
        }
        toast.show();
    }
}

8
7
0

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
8
7