我读到使用 ui 保留片段和对视图的引用会导致内存泄漏。比我创建带有片段的测试应用程序,我在视图上存储一些引用并设置 setRetaineInstance(true),但是几次屏幕旋转不会导致任何泄漏。MAT 说我只有一个父活动实例。我做错了什么?在哪些情况下使用 ui 保留片段会导致泄漏?
RetainInstanceActivity.java
public class RetainInstanceActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, RetainFragment.newInstance())
.commit();
}
}}
RetainFragment.java
public class RetainFragment extends Fragment {
private View mLogin;
private View mPassword;
private View ImageView;
public static RetainFragment newInstance() {
final RetainFragment fragment = new RetainFragment();
return fragment;
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(final LayoutInflater inflater,
final ViewGroup container, final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_retain, container,
false);
mLogin = view.findViewById(R.id.login);
mPassword = view.findViewById(R.id.password);
ImageView = view.findViewById(R.id.img);
return view;
}
}