2015-10-14 52 views
0

我有一個創建自定義按鈕的活動。 這是按鈕類。自定義按鈕onClickListener是靜態conext?

在我的主要活動中,我有方法允許程序在活動之間跳轉,但是我得到的錯誤是我從靜態上下文中引用非靜態方法。這是爲什麼?不是按鈕一個新的實例?

public class LoginButton extends Button { 

private DataAdapter myDataAdapter; 

private String LOG_TAG = "Login Button"; 

private EditText myPasswordEditText; 
private EditText myUserEditText; 

Context ctx; 


public LoginButton(Context ctx, AttributeSet attrs) { 
    super(ctx, attrs); 

    this.ctx = ctx; 

    setOnClickListener(clicker); 
    myDataAdapter = new DataAdapter(ctx); 
} 


//Other way is to implement the OnClickListener and implement the onClick method. 
OnClickListener clicker = new OnClickListener() { 
    public void onClick(View v) { 

     if(CheckUsernameField() && CheckPasswordField()){ 

      myDataAdapter.open(); 

      if(myDataAdapter.LoginToDB(myUserEditText.getText().toString(), myPasswordEditText.getText().toString())){ 

       //TODO: Custom buttons have trouble getting context. My solution was to call different activities from static method, but that requires setting FLAG_ACTIVITY_NEW_TASK which is not recommended. 
       MainActivity.GoToBeginRunScreen(ctx); 
       CreateAlertDialog("Login successful"); 
      } 
      else 
       CreateAlertDialog("Invalid username and password"); 

      myDataAdapter.close(); 

     } 
     else 
      CreateAlertDialog("Please enter a username and password"); 

    } 
}; 

這是我從上面的按鈕調用的代碼。

public void GoToBeginRunScreen(Context ctx){ 
    Intent intent = new Intent(ctx, BeginRunActivity.class); 
    ctx.startActivity(intent); 
} 
+0

錯誤在MainActivity.GoToBeginRunScreen(ctx)發生; – Spectrem

+0

如何直接訪問GoToBeginRunScreen它不是靜態的 – Pavan

+0

((MainActivity)ctx).GoToBeginRunScreen(ctx);做這個 – Pavan

回答

3

您無法通過類直接訪問非靜態方法,你必須在這種情況下,你必須使用上下文中使用類(活動)當前實例創建類的實例,這樣只是把

((MainActivity)ctx).GoToBeginRunScreen(ctx); 

簡單在您的要求,您就可以直接調用

Intent intent = new Intent(ctx, BeginRunActivity.class); 
    ctx.startActivity(intent); 
在點擊監聽

因爲你保持上下文

+0

哇。我不相信我沒有想到這一點。有了這個解釋,現在對我來說很明顯。 – Spectrem

+0

因此(MainActivity)指定MainActivity ctx? – Spectrem

+0

@Spectrem看到編輯可能會更好,你直接調用那裏,如果只有需求調用新的活動 – Pavan