我想模块化我的类的用法,但是我在传递函数时遇到问题。我希望能够通过一个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
我觉得这里有些不正确。你能简单地描述一系列点击按钮的事件吗? –
你在第二种情况下得到的例外是什么? ''!这里是错误,异常抛出' –