2016-02-25 194 views
0

嘿傢伙我是Android的開發新手和項目,我必須實現一個按鈕的監聽器。 但不幸的是,他無法檢測到我認爲的按鈕。 這裏是Java代碼:Android Button監聽器實現

public class Touch extends AppCompatActivity implements OnTouchListener,OnClickListener { 


private button boutonCompteur = null; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 

    super.onCreate(savedInstanceState); 
    setContentView(R.id.Compteur); 
    boutonCompteur = (button) findViewById(R.id.Compteur); 
    boutonCompteur.setOnTouchListener(this); 
    boutonCompteur.setOnClickListener(this); 

} 

@Override 
public boolean onTouch(View v, MotionEvent event) 
{ 
    return true; 
} } 

這裏是XML:

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="appuyez ici pour compter votre nombre de touch" 
    android:id="@+id/Compteur" 
    android:height="130dp" 
    android:textColor="#1818e3" 
    android:textColorHighlight="#cd5555" 
    android:textSize="22dp" 
    android:textStyle="italic" 
    android:layout_marginTop="150dp" 
    android:layout_alignParentStart="true" /> 

謝謝您的回答:)

+1

您不需要將onTouch和onClick都添加到按鈕。只是使用onClick –

+0

試試這個:http://stackoverflow.com/questions/25803727/android-setonclicklistener-method-how-does-it-work(setOnClickListner);或從官方文檔:http://developer.android.com/reference/android/widget/Button.html – KickingLettuce

+0

感謝您的答案,這真的很有幫助!我學到的東西感謝你們:) – Matnako

回答

2

我將用一些視覺上的幫助回答你的問題,並確定爲什麼不工作 ... 看看下面並注意形象:

  1. 你需要一個佈局來活動和這是不一樣的按鈕
  2. 你需要找到佈局中的按鈕,這是由你在xml文件中使用的id odne,並且不是相同的佈局!
  3. 您需要設置分辯監聽得到的onclick,Android已經爲括號之間的OnClickListener接口
  4. 字按鈕是一個鑄件,(Android將嘗試的東西轉化爲一類,因此類是類按鈕,而不是變量的名稱)
  5. 您在onClick中編寫的所有代碼是按下按鈕後將執行的代碼。

enter image description here


結論

以圖像爲參考,並在代碼中實現它。

+0

感謝您的回答,這真的很有幫助,我學到的東西感謝你:) – Matnako

0

刪除onTouch,只能使用onClick

刪除此行

boutonCompteur.setOnTouchListener(this); 

,改變public boolean onTouch(View v, MotionEvent event)

public void onClick(View v) { 
      // Do whatever you want 
     } 

,改變private button boutonCompteur = null;private Button boutonCompteur;。 (我不認爲在做按鈕聲明時你需要添加=null)。

+1

謝謝你的回答。我沒有閱讀整個安卓課程,所以我不知道我只需要onClick。無論如何,再次感謝這麼快的答案:D – Matnako