如何在点击edittext上播放声音

时间:2016-03-19 10:03:39

标签: android android-layout material-design

我想在onc​​lick eddittext上播放声音。但是我在单击edittext上播放声音时遇到问题。它从第二次点击开始工作。而且我不想从edittext中删除焦点。请帮帮我。

 <LinearLayout
    android:id="@+id/res3"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

 <android.support.design.widget.TextInputLayout
    android:id="@+id/input_layout_mail"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

 <EditText
     android:id="@+id/mail"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:singleLine="true"
     android:textSize="20sp"
     android:maxLength="50"
     android:inputType="textEmailAddress"
     android:hint="@string/mailid" />
 </android.support.design.widget.TextInputLayout>
 </LinearLayout>

这是我的Java代码

emailid.setOnTouchListener(new View.OnTouchListener() {
         @Override
         public boolean onTouch(View v, MotionEvent event) {
             playSound("click.mp3");
             return false;
         }
     });
public void playSound(final String p_fileName)
     {
    try
     {

        if (m_player != null && m_player.isPlaying())
        {
            m_player.stop();
            m_player.release();
            m_player = null;
        }
        else
        {
            m_player.release();
        }

        m_player = new MediaPlayer();
        m_player.reset();
        AssetFileDescriptor m_descriptor = getAssets().openFd(p_fileName);
        m_player.setDataSource(m_descriptor.getFileDescriptor(), m_descriptor.getStartOffset(), m_descriptor.getLength());
        m_descriptor.close();

        m_player.prepare();
        m_player.setVolume(1f, 1f);
        m_player.setLooping(false);

            m_player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

            }
        });
        m_player.start();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用OnFocusChangeListener来处理EditeText:

 emailid.setOnFocusChangeListener(new OnFocusChangeListener() {          

    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            playSound("click.mp3");
        }
    }
});

答案 1 :(得分:0)

第一次点击会input消耗吗?尝试将监听器放在TextInputLayoutTextInputLayout上。就个人而言,我也会使用EditText而不是OnClickListener