2014-05-16 66 views
1

所以我嘗試做一個簡單的圖像按鈕:onClickListener問題

<ImageButton 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/button_image" 
    android:contentDescription="@string/desc/> 

XML:

public class MainActivity extends ActionBarActivity { 
protected void onCreate1 (Bundle savedInstaceState){ 
    Bundle savedInstanceState; 
    super .onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Button button1 = (Button) findViewById (R.id.button1); 

      View.setOnClickListener(new onClickListener() { 
       public void onClick (View v) { 
        Toast.makeText(v.getContext(), "You clicked it. Genius.", Toast.LENGTH_SHORT).show(); 
       } 
      }); 

但它不斷彈出錯誤:"The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new onClickListener(){})"

我進口android.view.View.OnClickLIstener;

import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v7.app.ActionBarActivity; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.Toast; 
import android.view.View.OnClickListener; 
+0

button1.setOnClickListener(... – dymmeh

+0

也投給自己的ImageButton – Raghunandan

+0

@dymmeh同樣的錯誤出現:/ – Andy

回答

2

,你應該這樣做:

button1.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

      } 
     }); 

使用Button1的和檢查OnClickListener外殼。

+0

還是同樣的錯誤「,在類型視圖的方法setOnClickListener(View.OnClickListener)不適用於參數(新的onClickListener(){})「 – Andy

+0

您是否在編譯之前保存Java文件?錯誤消息顯示」onClickListener「,而您的代碼現在使用」OnClickListener「。 – cybersam

1

使用onClickListener使用此代碼

 Button bTutorial1 = (Button) findViewById(R.id.tutorial1); 
    bTutorial1.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 


     } 
    }); 
0

首先要知道的是,一個onclick處理程序實現的接口View.OnClickListener。您需要創建一個實現接口的類,因爲您需要添加執行的代碼。 。

onClickListener應使用如下:

Button button1 = (Button) findViewById (R.id.button1); 

     View.setOnClickListener(new onClickListener() { 
      public void onClick (View v) { 
       Toast.makeText(v.getContext(), "You clicked it. Genius.", Toast.LENGTH_SHORT).show(); 
      } 
     }); 

OR

通過創建類內嵌如下:

findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { 
@Override 
public void onClick(View v) { 
    //Inform the user the button has been clicked 
    } 

});

相關問題