将Context/Activity实例保留在RecyclerView.Adapter中是否安全? [英] Is it leak-safe to keep a Context/Activity instance in RecyclerView.Adapter?

查看:108
本文介绍了将Context/Activity实例保留在RecyclerView.Adapter中是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出这样的适配器:

public class MyAdapter extends RecyclerView.Adapter {

    private final Activity mActivity;
    private final List<Item> mItemList;

    public MyAdapter(Activity activity, List<Item> itemList) {
        this.mActivity = activity;
        this.mItemList = itemList;
    }

    //[...]

    public void onBindViewHolder(ViewHolder holder, int position) {
        final Item i = mItemList.get(position);
        holder.launchButton.setOnClickListener(new OnClickListener() {
                @Override public void onClick(View v) {
                    mActivity.startActivity(i.getIntent());
            });
    }

}

如您所见,启动实例需要活动实例.当然,还有其他方法可以做到这一点(例如,使用接口),但问题的关键是在适配器中保留对mActivity实例的硬引用是否安全

As you can see, the activity instance is needed for launch the intents. Of course, there are other ways to do that (e.g. using interfaces) but the point of the question is if it is safe to keep the hard reference to mActivity instance in the adapter

推荐答案

是的,很好.一旦没有从根对象强烈引用对象,Android的垃圾回收将回收对象.该适配器由RecyclerView引用,并且在释放该Activity之前,该RecyclerView将符合垃圾回收的条件,因此,在应回收该Activity时,该RecyclerView将符合垃圾回收的条件,因此不会阻止垃圾回收.从垃圾收集活动.同样,如果Activity引用了适配器,这很好,就像两个对象仅相互引用一样,无法从根对象访问它们,因此都可以进行垃圾回收.

Yes, it's fine. Android's garbage collection will recycle objects once there is no strong reference to them from the root object. The adapter is referred to by the RecyclerView, and the RecyclerView will be eligible for garbage collection before the Activity is freed, so by the time the Activity should be recycled, the RecyclerView will be eligible for garbage collection, and thus it will not prevent the Activity from being garbage collected. Also, this is fine if the Activity has a reference to the Adapter, as if two objects only have references to each other, they cannot he accessed from the root object, and thus are both eligible for garbage collection.

这篇关于将Context/Activity实例保留在RecyclerView.Adapter中是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆