java 视图中的 OnTouchListener - Android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16506287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OnTouchListener in a View - Android
提问by KeirDavis
When I am adding a listener 'OnTouchListener' to a View, it doesn't register. Here is my code:
当我向视图添加侦听器“OnTouchListener”时,它不会注册。这是我的代码:
GUI gui;
boolean guis = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gui = new GUI(getBaseContext());
gui.setOnTouchListener(this);
setContentView(gui);
}
When I do setOnTouchListener(), I put 'this' as a parameter.. Should that be something else?
当我执行 setOnTouchListener() 时,我将“this”作为参数。那应该是别的东西吗?
I let the GUI class implement OnTouchListener and adds a OnTouch method... But I put
我让 GUI 类实现 OnTouchListener 并添加了一个 OnTouch 方法......但我把
Log.w("AA","Hello")
In the OnTouch method, yet it doesn't log that at all.
在 OnTouch 方法中,它根本不记录。
回答by Raghunandan
You can do the following
您可以执行以下操作
public class MainActivity extends Activity implements OnTouchListener{
GUI gui;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gui = new GUI(MainActivity.this);
setContentView(gui);
gui.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Log.w("AA","Hello")
return true;
}
Or you can override the onTouch in your gui view
或者您可以在 gui 视图中覆盖 onTouch
public class GUI extends View{
Context mcontext;
public MyView(Context context) {
super(context);
mcontext=context;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Toast.makeText(mcontext, "View clicked", 1000).show();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// do something
break;
case MotionEvent.ACTION_MOVE:
// do something
break;
case MotionEvent.ACTION_UP:
//do something
break;
}
return true;
}
As Luksprog commented this refer's to the current context.
正如 Luksprog 所评论的,这是指当前的上下文。
If you do this gui.setOnTouchListener(this);
如果你这样做 gui.setOnTouchListener(this);
Your activity class must implement OnTouchListener and override onTouch method.
您的活动类必须实现 OnTouchListener 并覆盖 onTouch 方法。
You can also Override onTouch in your custom view.
您还可以在自定义视图中覆盖 onTouch。
There is no need to implement OnTouchListener in you GUI custom view class if you just override onTouch.
如果您只是覆盖 onTouch,则无需在您的 GUI 自定义视图类中实现 OnTouchListener。