[TipToast]修正TipToast内存泄漏
This commit is contained in:
@@ -17,6 +17,13 @@ import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.core.view.ViewCompat;
|
||||
import androidx.lifecycle.Lifecycle;
|
||||
import androidx.lifecycle.LifecycleEventObserver;
|
||||
import androidx.lifecycle.LifecycleOwner;
|
||||
|
||||
import com.mogo.eagle.core.utilcode.kotlin.ExtensionsKt;
|
||||
import com.mogo.eagle.core.utilcode.mogo.logger.Logger;
|
||||
|
||||
|
||||
@@ -34,7 +41,7 @@ public final class TipToast {
|
||||
private static ToastViewGenerator sGenerator;
|
||||
|
||||
public static void init( Context context, ToastViewGenerator generator ) {
|
||||
TipToast.sContext = context;
|
||||
TipToast.sContext = context.getApplicationContext();
|
||||
sHandler = new Handler( context.getMainLooper() );
|
||||
sGenerator = generator;
|
||||
}
|
||||
@@ -165,20 +172,21 @@ public final class TipToast {
|
||||
|
||||
sHandler.post(() -> {
|
||||
synchronized ( sSyncObject ) {
|
||||
|
||||
if ( context == null ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( sToast != null ) {
|
||||
sToast.cancel();
|
||||
if ( sToast != null) {
|
||||
View view = sToast.getView();
|
||||
if (view != null && ViewCompat.isAttachedToWindow(view)) {
|
||||
sToast.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
if ( sGenerator == null ) {
|
||||
sToast = Toast.makeText( context, msg, duration );
|
||||
} else {
|
||||
sToast = new Toast( context );
|
||||
final View view = sGenerator.make( context, msg, tipDrawable );
|
||||
|
||||
if ( view != null ) {
|
||||
sToast.setView( view );
|
||||
sToast.setGravity( sGenerator.gravity(), sGenerator.xOffset(), sGenerator.yOffset() );
|
||||
@@ -187,6 +195,15 @@ public final class TipToast {
|
||||
sToast = Toast.makeText( context, msg, duration );
|
||||
}
|
||||
}
|
||||
View view = sToast.getView();
|
||||
if (view != null) {
|
||||
LifecycleOwner lifecycleOwner = ExtensionsKt.getLifecycleOwner(view);
|
||||
lifecycleOwner.getLifecycle().addObserver((LifecycleEventObserver) (source, event) -> {
|
||||
if (event == Lifecycle.Event.ON_DESTROY) {
|
||||
sToast = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
if ( sToast != null ) {
|
||||
sToast.show();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user