Toastをカスタマイズする
|デフォルトのToastはテキストを表示するだけのシンプルなものですが、
下の図のようにテキストと一緒に画像を表示するなど、ちょっと凝ったToastを作ることも可能です。
今回はToastのカスタマイズ方法についてご紹介したいと思います。
詳細は続きからどうぞ。
レイアウトの定義
カスタマイズしたToastを作るには、まずToastのレイアウトを定義します。
上の図のようなレイアウトにしたい場合、以下のようなxmlファイル(toast_layout.xml)を作成します。
ImageViewとTextViewを定義しておきます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | android:orientation = "horizontal" android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:padding = "10dip" android:background = "#FFFFFF" > < ImageView android:id = "@+id/image" android:layout_width = "64dip" android:layout_height = "64dip" android:layout_marginRight = "10dip" /> < TextView android:id = "@+id/text" android:layout_width = "wrap_content" android:layout_height = "fill_parent" android:textColor = "#000000" /> </ LinearLayout > |
Toastにカスタムレイアウトを設定する
プログラム上ではLayoutInflater#inflateメソッドを使ってtoast_layout.xmlからViewを作成します。
LayoutInflaterクラスはxmlファイルの定義に従ってViewを生成する際に利用されるクラスで、
LayoutInflater#inflateメソッドを使うと指定したxmlファイルから動的にViewを生成することが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 | // インフレータを取得する LayoutInflater inflater = getLayoutInflater(); // カスタムToast用のViewを取得する View layout = inflater.inflate(R.layout.toast_layout, null ); // ImageViewを取得して任意のイメージを設定する ImageView image = (ImageView) layout.findViewById(R.id.image); image.setImageResource(R.drawable.img001); // TextViewを取得して任意のテキストを設定する TextView text = (TextView) layout.findViewById(R.id.text); text.setText( "このようにToastをカスタマイズできます。" ); |
getLayoutInflaterメソッドを使ってLayoutInflaterを取得し(2行目)、
LayoutInflater#inflateメソッドでtoast_layout.xmlからViewを作成しています(5行目)。
生成したViewを使えばImageViewとTextViewに画像とテキストを設定することができます(8, 12行目)。
あとはToast#setViewメソッドでカスタマイズしたレイアウトを設定してToastを表示します。
1 2 3 4 | // Toastにカスタマイズしたレイアウトを設定して表示する Toast toast = new Toast( this ); toast.setView(layout); toast.show(); |
以上、おつかれさまでした。
2 Comments