2011-04-01 97 views
5

我在android應用開發的新手。 我使用http://developer.android.com/resources/tutorials/views/hello-formstuff.html給出的形式的東西的例子。在這個我已經使用自定義按鈕的例子。自定義按鈕例如不工作

我的代碼如下:

package com.example.helloformstuff; 

    import android.app.Activity; 
    import android.content.DialogInterface.OnClickListener; 
    import android.os.Bundle; 
    import android.view.View; 
    import android.widget.Button; 
    import android.widget.Toast; 

    public class HelloFormStuff extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     final Button button = (Button) findViewById(R.id.button); 
     button.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) { 
       // Perform action on clicks 
       Toast.makeText(HelloFormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show(); 
      } 
     });  

    } 
    } 

它顯示以下錯誤:

The type new DialogInterface.OnClickListener(){} must implement the inherited 
    abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int) 
    - The method setOnClickListener(View.OnClickListener) in the type View is not 
    applicable for the arguments (new DialogInterface.OnClickListener(){}) 

我無法弄清楚這種錯誤的原因。

請幫我解決這個問題。

感謝

潘卡

回答

1

進口android.view.View.OnClickListener

代碼的其餘保持不變將完全執行的代碼替代進口android.content.DialogInterface.OnClickListener 。

+0

你知道爲什麼這樣寫嗎?爲什麼不能只有一個聽衆? – user219882 2012-03-05 20:30:06

1

你實現了錯誤的OnClickListener。嘗試View.OnClickListener:

button.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // Perform action on clicks 
      Toast.makeText(HelloFormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
+0

感謝扎克的答覆使用您的代碼,我不得不刪除進口android.content.DialogInterface.OnClickListener; 因爲我已經導入視圖? – 2011-04-01 10:53:49

3

您使用的是錯誤的OnClickListener。使用此代碼來代替:

button.setOnClickListener(new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      // Perform action on clicks 
      Toast.makeText(HelloFormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
+0

感謝Roflcoptr的答覆。我已經根據您的建議修改了代碼,但我現在正在跟蹤錯誤: - DialogInterface無法解析爲類型 \t - 類型View中的方法setOnClickListener(View.OnClickListener)不是 \t適用於參數OnClickListener(){}) – 2011-04-01 10:51:59

+0

你有進口包android.content?你也可以使用android.content.DialogInterface.OnClickListener – RoflcoptrException 2011-04-01 10:54:33

+0

是的,你可以從上面的代碼我已經導入了android.content.DialogInterface.OnClickListener – 2011-04-01 10:55:56