我有一个(看似)简单的问题:我试图在子线性布局上设置onTouchListener,但我无法编译代码。我收到错误"无法解析符号setOnTouchListener"当我尝试在我选择的视图上使用setOnTouchListener()时。
如何记录LinearLayout上的触摸?我做错了什么?
MainActivity.java
public class MainActivity extends FragmentActivity {
public static LinearLayout glView;
public static OpenGL_GLSurface foo;
public TouchController touchSurface;
void configView(){ // used to configure an opengl view
foo = new OpenGL_GLSurface(this);
setContentView(R.layout.activity_main);
glView = (LinearLayout)findViewById(R.id.openglsurface);
RelativeLayout.LayoutParams glParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
glView.addView(foo, glParams);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
touchSurface = new TouchController(this); //initialize touchable surface
}}
TouchController.java
public class TouchController {
private Context mContext;
public TouchController(Context c) { //constructor
mContext = c;
}
View.OnTouchListener touch = new View.OnTouchListener() { //set OnTouchListener to OpenGL View
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (maskedAction) {
//do stuff
}
return true;
}
};
MainActivity.glView.setOnTouchListener(touch); //Compilation Error here @ setOnTouchListener
}
答案 0 :(得分:1)
问题出在TouchController中,当您设置触控侦听器时,此行:
MainActivity.glView.setOnTouchListener(touch);
这行代码是无效的java代码,因为它只是在类中闲逛。它必须位于构造函数之类的方法中。像这样:
修改强>
public class TouchController {
private Context mContext;
public TouchController(Context c) { //constructor
mContext = c;
View.OnTouchListener touch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (maskedAction) {
//do stuff
}
return true;
}
};
//Register touch listener here in constructor or in another method
CourseListActivity.glView.setOnTouchListener(touch);
}
}
您应该考虑移动成员变量的分配"触摸"在构造函数内部,就在设置触摸侦听器之前。它会更有条理。