[英]Pass an interface between activities in intent
I have this situation: a Class A (that implements interface I), a Modal and a Class B (that implements interface I).我有这种情况:一个 Class A(实现接口 I),一个 Modal 和一个 Class B(实现接口 I)。
The Class A open the modal, and from the modal I go to class B. In class BI want to return to the Class A with the Modal updated (Not implemented yet). The Class A open the modal, and from the modal I go to class B. In class BI want to return to the Class A with the Modal updated (Not implemented yet).
I'm trying to pass an interface between the two activities but I recive this error (I already extends Serializable in Interface):我试图在两个活动之间传递一个接口,但我收到了这个错误(我已经在接口中扩展了 Serializable):
Caused by: java.io.NotSerializableException: com.google.android.material.textview.MaterialTextView
Class A Class A
@Override
public void showList() {
Intent intent = new Intent(this, SelectMethod.class);
intent.putExtra("iHome", this);
startActivity(intent);
}
Modal模态
# Function when click button and go to the class B
btn_select_method.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
iHome.showList();
}
});
Class B (SelectMethod) Class B(选择方法)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
intent.getSerializableExtra("iHome");
}
Interface界面
public interface Ihome extends Serializable {
void showList();
}
To a class be serializable all of this fields need to be serializable (can write/read keeping state), any class that extends View have fields that are not serializable like Contexts and Listeners, those are instances.对于 class 可序列化,所有这些字段都需要可序列化(可以写入/读取保持状态),任何扩展 View 的 class 具有不可序列化的字段,如上下文和侦听器,这些是实例。
You should not try to pass the activity/views/fragments instances trough intents since it breaks android lifecycle behaviour.您不应尝试通过意图传递活动/视图/片段实例,因为它会破坏 android 生命周期行为。
Since you using a Activity with modal theme, you may use由于您使用带有模态主题的活动,您可以使用
startActivityForResult(intent, 25 /*any number */)
Then into SelectMethod instead of calling a method from the FirstActivity you setResult
then finish
然后进入 SelectMethod 而不是从您
setResult
的 FirstActivity 调用方法然后finish
The result is read from FirstActivity into:结果从 FirstActivity 读入:
@Override public void onActivityResult
See more: https://developer.android.com/training/basics/intents/result#kotlin查看更多: https://developer.android.com/training/basics/intents/result#kotlin
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.