我想模块化我的类的使用,但我在传递函数时遇到问题。我希望能够将 OnClickListener 从 1 个 Activity 传递到此 CoachmarkActivity。
我尝试了两种不同的方法: 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# 中传递一个委托(delegate)对象(变量形式的函数),但在 Android Java 中。
有什么想法吗?谢谢。
最佳答案
您正在尝试向您的 Intent 添加一个额外的 Serializable
,但是 OnClickListener
没有实现该接口(interface)。您可以通过创建一个实现您需要的两个接口(interface)的类来实现您想要的。
private class SerializableClickListener implements View.OnClickListener, Serializable {
@Override public void onClick() {
// TODO handle click
}
}
但是,仅仅因为你可以并不意味着你应该。将点击监听器发送到另一个 Activity 是一种可怕的代码味道,您真的应该重新考虑如何通过 Intents/Broadcasts 来做到这一点。
关于java - 如何将 onClick 函数传递给 Intent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36491728/