2015-06-24 29 views
4

如何在LinearLayout中一次添加事件OnTouchListenerOnclickListener如何在Linear Layout中一次添加OnTouchListener和OnClickListener?

這裏是我的代碼,但不工作

final LinearLayout llTimeTable=(LinearLayout) findViewById(R.id.llSehriIftar); 
    llTimeTable.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      Intent intent = new Intent(MainActivity.this, Ramadandate.class); 
      startActivity(intent); 

     } 
    }); 
    llTimeTable.setOnTouchListener(new View.OnTouchListener() { 

     @Override 
     public boolean onTouch(View v, MotionEvent event) { 

      switch (event.getAction()) { 
      case MotionEvent.ACTION_DOWN: 

      llTimeTable.setBackgroundColor(Color.rgb(51, 51, 255)); 
       break; 

      case MotionEvent.ACTION_UP: 

       // set color back to default 
       llTimeTable.setBackgroundColor(Color.rgb(76, 106, 225)); 

       break; 
      } 
      return true; 
     } 
    }); 

但是,當我只用OnclickListener它的工作原理,當我只用onTouch方法它的工作原理,但兩者在同一時間不能正常工作。

+0

你的概念不清晰觸摸和點擊,請閱讀第一 –

+0

http://stackoverflow.com/questions/11578718/how-to-combine-onclicklistener-and-ontouchlistener-for-an-imagebutton – Karthik

+0

您可能需要看看這個。我認爲這有助於掌握onTouch vs onClick http://stackoverflow.com/a/9123001/1239911 – Amt87

回答

7

由於Touch事件更爲普遍,因此先調用它,然後onClick被觸發,但是,由於您的onTouch返回true,事件將被消耗且永遠不會到達onClick

簡單地改變onTouchreturn false和你的onClick將被調用。

+1

非常感謝.. –

+1

沒問題!很高興我幫了 –

+1

第一個正確的應該打勾;) – Amt87

3
llTimeTable.setOnTouchListener(new View.OnTouchListener() { 

     @Override 
     public boolean onTouch(View v, MotionEvent event) { 

     //Your code....... 
      return false; 
     } 
    }); 

確保您在TouchListener返回false監守如果返回true那麼該事件將不會被傳遞到其他的聽衆。

相關問題