按住按钮时振动

Luc*_*cas 15 android button vibration android-vibration

我正在制作一个应用程序,用户按住一个按钮,使手机振动,我不知道如何制作,所以只有当按钮按下它振动,我的代码到目前为止.

package one.two.bn;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;



    public class Vb extends Activity {
            /** Called when the activity is first created. */
        private Button button1;
        private Vibrator vibrator;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            button1 = (Button)findViewById(R.id.button1);
            button1.setOnClickListener(new View.OnClickListener() {
            Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);    
        public void onClick(View v) {
                if(v==button1){ 
                vibrator.vibrate(300000);           
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果有任何可以帮助感谢很多.

Bip*_*alu 67

试试这个代码

Vibrator vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE) ;
Run Code Online (Sandbox Code Playgroud)

然后在OnClickListener你的按钮:

vibe.vibrate(50); // 50 is time in ms
Run Code Online (Sandbox Code Playgroud)

并且不要忘记您需要向清单添加权限(在</application>标记之后):

<uses-permission android:name="android.permission.VIBRATE" />
Run Code Online (Sandbox Code Playgroud)

我也同意Tim,因为onTouchListener在点击之前被调用,所以它为你的应用程序提供最佳输出.


Yar*_*lyk 34

如果您需要像ActionMode或ContextMenu那样的长按反馈振动,

view.setOnLongClickListener(new View.OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
        v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        return true;
    }
});
Run Code Online (Sandbox Code Playgroud)


Foa*_*Guy 6

使用OnTouchListener()而不是onClick().

里面的侦听器时MotionEvent.getAction() == MotionEvent.ACTION_DOWN,你会打电话给vibrator.start(some arbitrarily large number here perhaps 1 minute or more)
getAction() == MotionEvent.ACTION_UP调用vibrator.cancel().

这样,它会开始,当你按下振动,当你抬起停止.


Muh*_*riq 0

在清单文件中添加振动权限。