android中处理内存泄漏,解决android中EditText导致的内存泄漏问题

开发中用到了LeankCanary,在一个简单的页面中(例如 :仅仅 包含Edittext),也会导致内训泄漏,为此,我在网上找了大量资料,最终解决。

例如一个布局:

android:layout_width="match_parent"

android:layout_height="match_parent"

android:focusable="true"

android:focusableInTouchMode="true"

android:orientation="vertical">

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_centerVertical="true"

android:layout_marginLeft="12dp"

android:background="@null"

android:hint="4-20位不包含特殊字符"

android:textSize="15dp" />

以上会导致内存泄漏,是由于EditText引用了Activity的context的原因,在Activity销毁的时候,

由于Edittext持有对Activity的context的引用,导致Activity无法正常回收。

解决办法:重写EditText,将对Activity中Context的引用,改为对ApplicationContext的引用。

代码如下:

@SuppressLint("AppCompatCustomView")

public class BaseEditText extends EditText {

private static java.lang.reflect.Field mParent;

static {

try {

mParent = View.class.getDeclaredField("mParent");

mParent.setAccessible(true);

} catch (NoSuchFieldException e) {

e.printStackTrace();

}

}

public BaseEditText(Context context) {

super(context.getApplicationContext());

}

public BaseEditText(Context context, AttributeSet attrs) {

super(context.getApplicationContext(), attrs);

}

public BaseEditText(Context context, AttributeSet attrs, int defStyleAttr) {

super(context.getApplicationContext(), attrs, defStyleAttr);

}

@SuppressLint("NewApi")

public BaseEditText(Context context, AttributeSet attrs, int defStyleAttr,

int defStyleRes) {

super(context.getApplicationContext(), attrs, defStyleAttr, defStyleRes);

}

@Override

protected void onDetachedFromWindow() {

try {

if (mParent != null)

mParent.set(this, null);

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

}

super.onDetachedFromWindow();

}

}

然后xml中的布局引用自定义的EditText:

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_centerVertical="true"

android:layout_marginLeft="12dp"

android:background="@null"

android:hint="4-20位不包含特殊字符"

android:textSize="15dp" />

另外,由于LinearLayout获取了焦点,也可能会导致内存的泄漏,

需要在Activity中的onDestroy里清除掉焦点:

LinearLayout.clearFocus();

再次测试,问题解决!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值