Android 按钮,长按音量加,抬起停止
时间: 2023-11-02 13:37:14 浏览: 51
你可以使用 Android 中的 GestureDetector.OnGestureListener 监听手势,然后在 onLongPress() 方法中执行音量加操作,并在 onUp() 方法中停止音量加操作。具体实现代码如下:
```
public class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private AudioManager audioManager;
private int streamType;
public MyGestureListener(Context context) {
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
streamType = AudioManager.STREAM_MUSIC;
}
@Override
public void onLongPress(MotionEvent e) {
audioManager.adjustStreamVolume(streamType, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
}
@Override
public boolean onUp(MotionEvent e) {
audioManager.adjustStreamVolume(streamType, AudioManager.ADJUST_SAME, AudioManager.FLAG_SHOW_UI);
return true;
}
}
```
然后在你的 Activity 中,创建 GestureDetector 对象并将其与你的 View 关联,如下所示:
```
GestureDetector gestureDetector = new GestureDetector(this, new MyGestureListener(this));
View view = findViewById(R.id.your_button);
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
```
这样,在你的按钮上长按并抬起手指时,音量会加,并在手指抬起后停止。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)