【问题标题】:Pass an interface from class to activity将接口从类传递到活动
【发布时间】:2016-05-26 01:55:20
【问题描述】:

如果我的类中有一个对象表单接口,我如何将它传递给活动?

我的解决方案是将其更改为静态对象,它工作正常,但有时它会由于垃圾收集器无法收集的所有旧引用而造成内存泄漏,并且我无法在我的界面上实现“Serializable”。

public class MyClass {
     protected OnStringSetListener onstringPicked;
        public interface OnStringSetListener {
            void OnStringSet(String path);

        }
    //......//
      public void startActivity(){
                Intent intent=new Intent(context,Secound.class);
                // ?! intent.putExtra("TAG", inter);
                context.startActivity(intent);
      }
}

【问题讨论】:

  • 使用Parcelable..它是为Android构建的..:)

标签: android android-intent interface serializable


【解决方案1】:

传入自定义对象有点复杂。您可以将类标记为可序列化 让 Java 来解决这个问题。但是,在 android 上,使用 Serializable 会严重影响性能。解决方案是使用 Parcelable。

Extra info

【讨论】:

    【解决方案2】:

    在我看来,使用Bundles 将是一个不错的选择。实际上捆绑包内部使用Parcelables。因此,这种方法将是一个很好的方法。

    假设您想将类型为 MyClass 的对象传递给另一个 Activity,您只需添加两个方法来压缩/解压缩到包。

    到捆绑:

    public Bundle toBundle(){
        Bundle bundle = new Bundle();
        // Add the class properties to the bundle
        return bundle;
    }
    

    来自捆绑包:

    public static MyClass fromBundle(Bundle bundle){
        MyClass obj = new MyClass();
        // populate properties here
        return obj;
    }
    

    注意:然后您可以使用putExtra 简单地将包传递给另一个活动。请注意,处理 bundle 比 Parcelables 简单得多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多