如何使用触摸听众并仅在触摸按钮时播放声音?

时间:2018-09-09 09:44:28

标签: java android button touch

我有一个带有按钮的应用程序,该按钮在单击时播放声音,在再次单击时暂停。现在,我希望此按钮仅在被触摸时播放声音,而在释放触摸时暂停。我的意思是:触摸并按住它会播放歌曲,取消触摸并停止播放歌曲,因此仅当用户触摸并按住它时才播放歌曲,而未按下按钮则不会播放。我什至希望只要触摸状态为true,就显示自定义按钮(图像),而一旦我不触摸它,就会显示默认的自定义按钮。 这是我主要活动的代码:

package com.example.firozkaoo2222.myapplication;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import static com.example.firozkaoo2222.myapplication.R.raw.police;

public class MainActivity extends AppCompatActivity {


private MediaPlayer policeSound;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button policeSounds = this.findViewById(R.id.police);

    policeSounds.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            int eventPadTouch = event.getAction();

            switch (eventPadTouch) {

                case MotionEvent.ACTION_DOWN:
                    // start playing sound , in your case:
                    policeSound.start();
                    return true;


                case MotionEvent.ACTION_UP:
                    // stop playing sound , in your case:
                    policeSound.stop();
                    return true;

            }
            return false;
        }
    });
}}

我的自定义button.xml的代码

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:state_pressed="true"
    android:drawable="@drawable/button_pressed" />
<item
    android:drawable="@drawable/button_default" />


</selector>

3 个答案:

答案 0 :(得分:1)

使用此代码段代替您的OnClickListener方法:

policeSounds.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

        if (policeSound == null) {
            policeSound = MediaPlayer.create(getApplicationContext(), R.raw.police);
        }

        int eventPadTouch = event.getAction();

        switch (eventPadTouch) {

            case MotionEvent.ACTION_DOWN:
                // start playing sound , in your case:
                policeSound.start();
                return true;


            case MotionEvent.ACTION_UP:
                // stop playing sound , in your case:
                policeSound.pause();
                return true;

        }
        return false;
    }
}

答案 1 :(得分:0)

尝试在您的onCreate()方法中添加它

policeSounds.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                if (event.getAction() == MotionEvent.ACTION_DOWN){ //The id check can be ignored since the listener is on the button already
                                    //play your sound
                                } else if (event.getAction() == MotionEvent.ACTION_UP){ //The id check can be ignored since the listener is on the button already
                                    //stop the sound
                                }
                                return true; //you need to return `true` otherwise it won't work
                            }
                        });

答案 2 :(得分:0)

如果我对您的理解正确,则需要使用setOnTouchListener而不是setOnClickListener,如果事件动作为ACTION_DOWN(按下按钮),则播放声音,并在事件动作为ACTION_UP(释放触摸)时停止声音:

client = MongoClient('mongodb://ip-addr:27017/user')
db = client['user']

x   = []
cur = db.user.find()
for i in cur:
    x.append(i)

newdata = {}    
for entry in x:
    numbers = entry.pop('numbers')
    numbers = numbers.replace("+","")
    domain = entry.pop('domain')
    newdata[numbers] = domain

def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
                        dialect=dialect, **kwargs)
for row in csv_reader:
    # decode UTF-8 back to Unicode, cell by cell:
    yield [unicode(cell, 'utf-8') for cell in row]

def utf_8_encoder(unicode_csv_data):
    for line in unicode_csv_data:
        yield line.encode('utf-8')


reader = unicode_csv_reader(codecs.open("201807_12_49333_N29069.csv", 
encoding="iso-8859-1"))
for row in reader:
    domain = row[2].encode('ascii') 
    domain = str(domain)
    domain = re.sub(domain, lambda find_all: newdata.get(find_all.group(0), domain), domain)
    row[2] = domain
    print(row[2], row[3])