2016-03-14 20 views
0

我有一個(看似)簡單的問題:我試圖在子線性佈局上設置onTouchListener,但我無法獲取我的代碼進行編譯。當我嘗試在我選擇的視圖上使用setOnTouchListener()時,出現錯誤「Can not Resolve Symbol setOnTouchListener」。Android在LinearLayout上捕獲觸及:無法解析符號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 
} 

回答

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

} 

你應該考慮移動構造函數中的成員變量「觸摸」的分配也設置了觸摸聽衆之前。它會更有組織。

+0

謝謝!你可以提供示例代碼來移動構造函數中的「touch」的賦值嗎?語法讓我有點困惑。 – Cody

+0

當然我編輯了答案。 – leonziyo