我想模塊化我的類的用法,但是我在傳遞函數時遇到問題。我希望能夠通過一個OnClickListener從1 activity到這個CoachmarkActivity。如何將onClick函數傳遞給Intent
我嘗試了2種不同的方法: 1.將OnClickListener傳遞給Intent 2.傳遞一個類FollowUpClass,實現Serializable方法,該方法的onClick方法。
您可以看到下面的代碼。這不是完整的代碼,但你應該能夠理解這一點。
public class CoachmarkActivity extends Activity {
public static final String RES_LAYOUT = "RES-LAYOUT";
public static final String LISTENER = "LISTENER";
public static final String FOLLOW_UP = "FOLLOW-UP";
@Override protected void onCreate(Bundle savedInstance) {
setContentView(getIntent.getIntExtra(RES_LAYOUT, R.layout.activity_default))
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
// 1ST ATTEMPT
// I want to modularize this
OnClickListener onClickPassedFromIntent = (OnClickListener) getIntent().getSerializableExtra(LISTENER);
button1.setOnClickListener(onClickPassedFromIntent);
// 2ND ATTEMPT
final FollowUpListener folllowup = (FollowUpListener) getIntent().getSerializableExtra(FOLLOW_UP);
button2.setOnClickListener(new OnClickListener() {
@Override void onClick() {
// !! Here is error, exception thrown
folllowup.onClick();
}
});
}
/**
* Public method to be used in other activity.
* Invocation wanna be:
* CoachmarkActivity.startThisActivity(getActivity(), R.layout.coachmark1, new OnClickListener() {
* @Override void onClick() {
* // Do something
* }
* });
*/
public static void startThisActivity(Context context, int resId, OnClickListener listener) {
Intent intent = new Intent(context, CoachmarkActivity.class);
intent.putExtra(RES_LAYOUT, resId);
// !! Line below is error, onClickListener is not serializable, no method can accomadate below
intent.putExtra(LISTENER, listener);
context.startActivity(intent);
}
/**
* Public method to be used in other activity.
* Invocation wanna be:
* CoachmarkActivity.startThisActivity(getActivity(), R.layout.coachmark1, new FollowUpListener() {
* @Override void onClick() {
* // Do something
* }
* });
*/
public static void startThisActivity(Context context, int resId, FollowUpListener folllowup) {
Intent intent = new Intent(context, CoachmarkActivity.class);
intent.putExtra(RES_LAYOUT, resId);
intent.putExtra(FOLLOW_UP, followup);
context.startActivity(intent);
}
}
抽象類:
public abstract class FollowUpListener implements Serializable {
public abstract void onClick();
}
的問題在源代碼上面的評論中陳述,具有標籤 「!!」 (只需CTRL + F「!!」)。我想要做的就像在C#中傳遞一個委託對象(函數的形式爲變量),但在Android Java中。
有什麼想法?謝謝。
你能告訴我從一個活動發送onClickListener到另一個活動的目的嗎? – Srinivasan
我覺得這裏有些不正確。你能簡單地描述一系列點擊按鈕的事件嗎? –
你在第二種情況下得到的例外是什麼? ''!這裏是錯誤,異常拋出' –