Androidプログラマへの道 〜 Moonlight 明日香 〜 - ビューをトースト表示する
トースト通知は, デフォルトでは文字列をポップアップ表示するが, ビューをポップアップ表示することもできる.



ビューのトースト通知

  • CustomToast.java
    • getLayoutInflaterメソッドで, LayoutInflaterのインスタンスを取得する.
    • LayoutInflater#inflaterメソッドで, custom_view.xmlの定義されたレイアウトのビューを生成する.
    • レイアウト内のメッセージ, アイコンを設定する.
    • Toastのインスタンスを生成する.
    • Toast#setViewメソッドで, ビューを設定する.
    • Toast#showメソッドで, ビューを表示する.
package com.moonlight_aska.android.customtoast;
import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CustomToast extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn = (Button)findViewById(R.id.button_id);
    btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        // ビューの作成
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.custom_view, null);
        // ビューの表示内容をセット
        TextView msg = (TextView)view.findViewById(R.id.msg_id);
        msg.sjavascript:void(0)etText("ビューのトースト表示だよ〜");
        ImageView icon = (ImageView)view.findViewById(R.id.icon_id);
        icon.setImageResource(R.drawable.moonlight);
        // Toastのインスタンスを生成
        Toast toast = new Toast(CustomToast.this);
        // ビューを設定
        toast.setView(view);
        // ビューを表示
        toast.show();
      }
    });
  }
}
  • res/custom_view.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="horizontal"
  android:background="#FFFFFF" >
  <ImageView android:id="@+id/icon_id"
    android:layout_width="96dip"
    android:layout_height="96dip"
    android:layout_marginRight="10dip"
    />
  <TextView android:id="@+id/msg_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
</LinearLayout>