gpt4 book ai didi

java - Android 捕获 LinearLayout 上的触摸 : Cannot Resolve Symbol setOnTouchListener.

转载 作者:行者123 更新时间:2023-12-01 10:14:32 25 4
gpt4 key购买 nike

我有一个(看似)简单的问题:我试图在子线性布局上设置 onTouchListener 但无法编译我的代码。当我尝试在所选 View 上使用 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
}

最佳答案

问题出在您的 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”的赋值移到构造函数内。它将更加有组织。

关于java - Android 捕获 LinearLayout 上的触摸 : Cannot Resolve Symbol setOnTouchListener.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35977927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com