2017-03-08 65 views
0

在我的應用程序中,當點擊按鈕時我要設置聲音,並且我使用了媒體播放器。但是,當我在很多活動中有很多按鈕時,它非常複雜,所以我想要創建一個按鈕類來擴展按鈕並在事件單擊按鈕中添加聲音。點擊時自定義按鈕類聲音

可能嗎?而且怎麼做呢?

+1

爲什麼不能嘗試這種方式來搜索? 1)Android中的自定義按鈕2)在事件 – Stallion

回答

0

試試這個,

 import android.content.Context; 
     import android.media.MediaPlayer; 
     import android.util.AttributeSet; 
     import android.util.Log; 
     import android.view.View; 
     import android.widget.Button; 

     public class CustomButton extends Button implements View.OnClickListener { 

      Context mContext; 
      public CustomButtonTest(Context context, AttributeSet attrs, int defStyle) { 
       super(context, attrs, defStyle); 
       mContext=context; 
       init(); 
      } 

      public CustomButtonTest(Context context, AttributeSet attrs) { 
       super(context, attrs); 
       mContext=context; 
       init(); 
      } 

      public CustomButtonTest(Context context) { 
       super(context); 
       mContext=context; 
       init(); 
      } 

      private void init(){ 
       setOnClickListener(this); 
      } 

      @Override 
      public void onClick(View v) { 
       // Do something 
       Log.d("TAG","@@@@@@@@@@ onClick"); 
       MediaPlayer mediaPlayer = new MediaPlayer(); 
       mediaPlayer = mediaPlayer.create(mContext, R.raw.xoay_touch_sound); mediaPlayer.start(); 


       /* 

       OR you can try below code also 
       */ 

       /*Log.d("TAG","@@@@@@@@@@ onClick"); 
       int MAX_SOUND_POOL_STREAMS = 4; 


       SoundPool soundPool = new SoundPool(MAX_SOUND_POOL_STREAMS, 
         AudioManager.STREAM_MUSIC, 100); 
       int mySoundId = soundPool.load(mContext, 
         R.raw.xoay_touch_sound, 1); 

       AudioManager audioManager = (AudioManager) mContext.getSystemService(mContext.AUDIO_SERVICE); 
       float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
       float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); 
       float volume = actualVolume/maxVolume; 
       soundPool.play(mySoundId, volume, volume, 1, 0, 1f);*/ 
      } 

     } 

XML

<yourPakageName.CustomButton 
     android:id="@+id/test" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     /> 
+0

上添加媒體播放器功能謝謝!但是當我添加代碼時: MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer = MediaPlayer.create(context,R.raw.xoay_touch_sound); mediaPlayer.start();在onClick它不運行 –

+0

這裏您使用MediaPlayer類..MediaPlayer.create(上下文,R.raw.xoay_touch_sound).........使用對象mediaPlayer .create(context,R.raw.xoay_touch_sound) – user2025187

+0

@ ĐờiCơbảnlàBuồn檢查更新的代碼。如果您的活動中編寫了OnClickListener,然後第一次刪除監聽器,然後運行代碼 – user2025187

相關問題