Android中實現帶聲音提示的Toast (自訂擴充Toast)

來源:互聯網
上載者:User

今天看到一個應用彈出的Toast的同時還 蹦擦個聲音 貌似還不錯。我說你別得瑟了,哥也搞個Toast也出來冒個聲 也來得瑟下。

這不,代碼奉上:

 

package weibo.lixiaodaoaaa.view;import weibo.lixiaodaoaaa.ui.R;import android.content.Context;import android.media.MediaPlayer;import android.util.DisplayMetrics;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.widget.TextView;import android.widget.Toast;/** * 帶聲音提示的Toast自訂 Toast控制項 *  * @author http://weibo.com/lixiaodaoaaa http://t.qq.com/lixiaodaoaaa * @version 0.1 * @created 2013-4-23 */public class MyToast extends Toast{   private MediaPlayer mPlayer;   private boolean isSound;   public MyToast(Context context)   {      this(context, false);   }   // isSound 表示是否播放音樂;;;;   public MyToast(Context context, boolean isSound)   {      super(context);      this.isSound = isSound;      mPlayer = MediaPlayer.create(context, R.raw.allsuccess);      mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()      {         @Override         public void onCompletion(MediaPlayer mp)         {            mp.release();// 釋放資源。讓資源得到釋放;;         }      });   }   @Override   public void show()   {      super.show();      if (isSound)      {         mPlayer.start();      }   }   /**    * 設定是否播放聲音    */   public void setIsSound(boolean isSound)   {      this.isSound = isSound;   }   /**    * 擷取控制項執行個體    *     * @param context    * @param text    *            提示訊息    * @param isSound    *            是否播放聲音    * @return    */   public static MyToast show(Context context, CharSequence text, boolean isSound, int duration)   {      MyToast result = new MyToast(context, isSound);      LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);      DisplayMetrics dm = context.getResources().getDisplayMetrics();      View v = inflate.inflate(R.layout.new_data_toast, null);      // v.setMinimumWidth(dm.widthPixels);// 設定控制項最小寬度為手機螢幕寬度      TextView tv = (TextView) v.findViewById(R.id.new_data_toast_message);      tv.setText(text);      result.setView(v);      result.setDuration(duration);// 設定 顯示多長時間;;;;      result.setGravity(Gravity.BOTTOM, 0, (int) (dm.density * 85));      return result;   }}



 

顯示效果如下:

測試工程 Demo執行個體下載(示範Demo下載)  猛擊這裡下載。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.