现在有以下的代码,想在另一个函数和另一个类中调用这个监听器,加入什么样的代码能实现这个功能啊?
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);
}
你需要创建一个类来继承监视器
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();
}
}
在Activity中要添加:
public class ListenerTestActivity extends Activity {
/** 当activity第一次被创建时要调用 */
@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));
}
}
例如创建一个类 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);
}