2012-09-30 19 views
1

我想捕獲java中的ImageButton併爲其定義一個onClick事件偵聽器。 但在捕獲行應用程序停止不知情。 使用即時通訊API級別8從佈局中捕獲按鈕時意外停止了錯誤

這是我的Java代碼:

import android.os.Bundle; 
import android.app.Activity; 
import android.graphics.PixelFormat; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.Window; 
import android.view.animation.Animation; 
import android.view.animation.TranslateAnimation; 
import android.widget.Button; 
import android.widget.ImageButton; 

public class Login extends Activity { 
    ImageButton buttonTest =(ImageButton)findViewById(R.id.imageButton1); 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 
     buttonTest.setOnClickListener(strLogoAnim); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_login, menu); 

     return true; 
    } 

    private OnClickListener strLogoAnim = new OnClickListener() { 

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

    @Override 
    public void onAttachedToWindow() { 
     super.onAttachedToWindow(); 
     Window window = getWindow(); 
     window.setFormat(PixelFormat.RGBA_8888); 
    } 

} 

即使我創建一個新項目,並測試它。但是這個問題存在了。 問題在哪裏?

回答

1
public class Login extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 
     ImageButton buttonTest =(ImageButton)findViewById(R.id.imageButton1); 
     buttonTest.setOnClickListener(strLogoAnim); 
    } 

試試這個。

+0

我已經嘗試過了,但存在的問題:( –

+0

@SajjadRad那麼你有東西在OnClickListener滑稽發佈你的logcat輸出 –

1

你需要引用的onCreate按鈕:

public class Login extends Activity { 
    ImageButton buttonTest; // remove this: =(ImageButton)findViewById(R.id.imageButton1); 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 
     buttonTest =(ImageButton)findViewById(R.id.imageButton1); // add this 
     buttonTest.setOnClickListener(strLogoAnim); 
    } 
+0

其工作。非常感謝 –