我有这段代码
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP) {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Random r=new Random();
int i1=(r.nextInt(500) +4000);
v.vibrate(i1);
}
return super.dispatchTouchEvent(ev);
}
我希望在另一个类和另一个函数中调用此侦听器。我该怎么称呼它?
答案 0 :(得分:2)
您需要创建一个实现侦听器的类
public class MyListener implements OnClickListener {
private Context context;
public MyListener(Context context) {
super();
this.context = context;
}
@Override
public void onClick(View v) {
Toast.makeText(context, "just a test", 2000).show();
}
}
在你的活动中:
public class ListenerTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new MyListener(this));
}
}
答案 1 :(得分:0)
创建一个名为MyUtils
的新类,并创建一个static public
方法来完成振动。然后,从您的侦听器调用此静态方法。
像:
public class MyUtils {
static public void vibrate(Context context) {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
Random r=new Random();
int i1=(r.nextInt(500) +4000);
v.vibrate(i1);
}
}
和
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP) {
MyUtils.vibrate(this);
}
return super.dispatchTouchEvent(ev);
}