我有一個創建自定義按鈕的活動。 這是按鈕類。自定義按鈕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);
}
錯誤在MainActivity.GoToBeginRunScreen(ctx)發生; – Spectrem
如何直接訪問GoToBeginRunScreen它不是靜態的 – Pavan
((MainActivity)ctx).GoToBeginRunScreen(ctx);做這個 – Pavan