I have a (seemingly) simple problem: I'm trying to set an onTouchListener on a child linear layout but I can't get my code to compile. I get the error "Cannot Resolve Symbol setOnTouchListener" when I try to use setOnTouchListener() on my chosen view.
How can I record touches on my LinearLayout? What am I doing wrong?
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
}
The issue is in your TouchController, when you are setting the touch listener, this line:
MainActivity.glView.setOnTouchListener(touch);
That line of code is invalid java code because is just hanging around in the class. It must be inside a method like the constructor. Like this:
Edit:
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);
}
}
You should consider moving the assignment of your member variable "touch" inside the constructor too, just before you set the touch listener. It will be more organized.