Skip to content

Instantly share code, notes, and snippets.

@yukpiz
Created February 7, 2014 04:32
Show Gist options
  • Save yukpiz/4b4a7a7dde85a2c1efc6 to your computer and use it in GitHub Desktop.
Save yukpiz/4b4a7a7dde85a2c1efc6 to your computer and use it in GitHub Desktop.

android.widget.Toast

  • Android Developer http://developer.android.com/intl/ja/reference/android/widget/Toast.html
Toast.LENGTH_LONG
View上での表示時間(長)
Toast.LENGTH_SHORT
View上での表示時間(短)

Toastの生成

  • Toastの生成にはmakeTextメソッドを利用する
//public static Toast makeText(Context context, CharSequence text, int duration)
Toast toast = Toast.makeText(this, "Hello, world!!", Toast.LENGTH_LOGN);

//public static Toast makeText(Context context, int resId, int duration)
Toast toast = Toast.makeText(this, R.string.message, Toast.LENGTH_LONG);
Public Methods(get, setで対応している説明は省略)
void
  • cancel()
  • 表示したToastを非表示にする。インスタンス化が必要。
int
  • getDuration()
int
  • getGravity()
float
  • getHorizontalMargin()
float
  • getVerticalMargin()
View
  • getView()
int
  • getXOffset()
int
  • getYOffset()
static Toast
  • makeText(Context context, CharSequence text, int duration)
  • Toastを生成する。第二引数に表示する文字列、第三引数に[LENGTH_LONG|LENGTH_SHORT]
static Toast
  • makeText(Context context, int resId, int duration)
  • Toastを生成する。第二引数にリソースID、第三引数に[LENGTH_LONG|LENGTH_SHORT]
void
  • setDuration(int duration)
  • 表示する時間を設定。[LENGTH_LONG|LENGTH_SHORT]
void
  • setGravity(int gravity, int xOffset, int yOffset)
  • 表示位置の設定。android.view.Gravity
void
  • setMargin(float horizontalMargin, float verticalMargin)
  • 検証したけど動きがいまいちわからない(位置指定ならsetGravityで)
void
  • setText(int resId)
  • 表示する文字列のリソースIDを指定。
void
  • setText(CharSequence s)
  • 表示する文字列を指定。
void
  • setView(View view)
  • 表示するViewを指定。
void
  • show()
  • 生成したToastを表示。

とりあえずサンプル

//とにかく最短で表示
Toast.makeText(this, R.string.message, Toast.LENGTH_SHORT).show();

//Toastを変数に取得して色々設定する
Toast toast = Toast.makeText(this, R.string.message, Toast.LENGTH_SHORT);

//表示時間を変更(Toast生成時に設定が必須)
toast.setDuration(Toast.LENGTH_LONG);
//表示位置を設定
toast.setGravity(Gravity.CENTER, 0, 0);
//表示文字列を変更(Toast生成時に設定が必須)
toast.setText("hogehoge");
//Viewも設定できる(カスタマイズViewを表示したり)
toast.setView(new View(this));
//Toastを表示する
toast.show();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment