Android 捕获 LinearLayout 上的触摸:无法解析符号 setOnTouchListener。

Android Capturing touches on LinearLayout: Cannot Resolve Symbol setOnTouchListener.

我有一个(看似)简单的问题:我试图在子线性布局上设置一个 onTouchListener,但我无法编译我的代码。当我尝试在我选择的视图上使用 setOnTouchListener() 时,出现错误 "Cannot Resolve Symbol 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
}

问题出在您的 TouchController 中,当您设置触摸侦听器时,这一行:

MainActivity.glView.setOnTouchListener(touch);

那行代码是无效的 java 代码,因为它只是徘徊在 class 中。它必须在构造函数之类的方法中。像这样:

编辑:

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);
    }

}

您应该考虑将成员变量 "touch" 的赋值也移到构造函数中,就在您设置触摸侦听器之前。这样会更有条理。