【问题标题】:Android Capturing touches on LinearLayout: Cannot Resolve Symbol setOnTouchListener.Android 在 LinearLayout 上捕获触摸:无法解析符号 setOnTouchListener。
【发布时间】:2016-03-14 01:01:36
【问题描述】:

我有一个(看似)简单的问题:我试图在子线性布局上设置一个 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
}

【问题讨论】:

    标签: java android opengl-es ontouchlistener touch-event


    【解决方案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);
        }
    
    }
    

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

    【讨论】:

    • 谢谢!你能给出在构造函数中移动“touch”赋值的示例代码吗?语法让我有点困惑。
    猜你喜欢
    • 2017-02-11
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2017-02-09
    相关资源
    最近更新 更多